[Tutor] python lists/nested lists
Steven D'Aprano
steve at pearwood.info
Sun Apr 14 04:08:06 CEST 2013
On 14/04/13 06:53, Soliman, Yasmin wrote:
> How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then subtract the avg from the original numbers in the list and print?
You calculate the average by summing the list, then dividing by the number of items.
To sum a list of numbers, use the sum() function.
total = sum(some_list)
To get the number of items, use the len() function.
num = len(some_list)
To divide, use the / operator. BUT beware, if you are using Python 2, there is a small problem with division: by default, Python will do integer division, which is not what you want. (Python 3 fixes this problem).
For example, if you say 17/3 in Python 2, you will get 5, instead of 5.666666666666667. You can fix that two ways: put this line at the very top of your program, before anything except comments:
from __future__ import division
Or, use floats instead of ints. If you say 17.0/3 you will get 5.666666666666667 as expected.
If you have a variable, you can convert it into a float using the float() function.
Once you have the average, you can print the differences like this:
for value in some_list:
print value - average
> Also, if I have a nested list:
> sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 'stom ache', 102.3]
>
> and I would like to print out all the patients with a temp > 100 how would I do so?
for record in sick_patients:
temp = ... # you have to fill this in, replace the dots with code
if temp > 100:
print record
How would you extract the temperature from the internal lists?
(Hint: the patient's name is record[0], their sex is record[1].)
--
Steven
More information about the Tutor
mailing list