In Python there are a number of built-in functions
that can be used on lists that allow you to quickly look through a list without
writing your own loops:
>>> numbers = [1, 52, 64, 72, 32] >>> print len(numbers) 5 >>> print max(numbers) 72 >>> print min(numbers) 1 >>> print sum(numbers) 221 >>> print float(sum(numbers))/len(numbers) 44.2
The sum() function can be applied only when elements
of the list are numbers otherwise you’ll get TypeError.
>>> guitars ['Gibson', 'Fender', 'Jackson'] >>> sum(guitars) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str'
The other functions that we uses such as max(), len()
work with lists of strings and other types that can be comparable.
Let’s rewrite an earlier program that computed the
average of a list of numbers entered by the user using a list.
First the program to compute an average without a
list:
total = 0 count = 0 while True: userinput = raw_input('Enter a number: ') if userinput == 'done' : break value = float(userinput) total = total + value count = count + 1 average = total / count print ‘Averge: ‘, average Enter a number: 5 Enter a number: 6 Enter a number: 7 Enter a number: 3 Enter a number: 4 Enter a number: 5 Enter a number: 63 Enter a number: 4 Enter a number: 5 Enter a number: 6 Enter a number: 7 Enter a number: done Average: 10.4545454545
In
this program we have to variables: count and sum. Their values before the start
of the while loop are equal to zero. Using while loop each time user enters a
number the value is added to the variable total and each entry is counted using
count variable. While loop can go forever because the condition is always True
so we simply added the if statement because we need to be able to stop the
program at some point. If user types a string done than the while loop is over
and execution of the program continues from calculating average value and
printing out the average value as result.
The
program could be simplified using built in functions to calculate sum and count
at the end using lists of course.
num = list() while True: userinput = raw_input('Enter a number: ') if userinput == 'done': break value = float(userinput) num.append(value) average = sum(num) / len(num) print 'Averge: ', average Enter a number: 5 Enter a number: 3 Enter a number: 4 Enter a number: 2 Enter a number: 6 Enter a number: 67 Enter a number: 232 Enter a number: 123125 Enter a number: 2312563 Enter a number: 21312523645 Enter a number: 123123123542 Enter a number: 23123123 Enter a number: 213123 Enter a number: 2 Enter a number: done
First
we’ve created a list called num and it’s an empty list. In while loop each time
the user enters a number the number is added to a list using append built in
function. At the end of a program, we simply compute the sum of the numbers in
the list and divide it by the count of the numbers in the list to come up with
the average value.
Nema komentara:
Objavi komentar