Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis- 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 Respostas
+ 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