- 5
Python function rainaverage(l) using tuples
Write a Python function rainaverage(l) that takes as input a list of rainfall recordings and computes the avarage rainfall for each city. The output should be a list of pairs (c,ar)where c is the city and ar is the average rainfall for this city among the recordings in the input list. Note that arshould be of type float. The output should be sorted in dictionary order with respect to the city name. Here are some examples to show how rainaverage(l) should work. >>> rainaverage([(1,2),(1,3),(2,3),(1,1),(3,8)]) [(1, 2.0), (2, 3.0), (3, 8.0)] >>> rainaverage([('Bombay',848),('Madras',103),('Bombay',923),('Bangalore',201),('Madras',128)]) [('Bangalore', 201.0), ('Bombay', 885.5), ('Madras', 115.5)]
2 odpowiedzi
+ 5
+ 2
This will do the stuff :-) Enjoy
def rainaverage(l):
data_dict={}
out=[]
for tup in l:
if tup[0] in data_dict:
data_dict[tup[0]].append(tup[1])
else:
data_dict[tup[0]]=[tup[1]]
for c in data_dict:
ar=sum(data_dict[c])/len(data_dict[c])
out.append(tuple([c,"%.2f" %ar]))
return out