Reputation: 717
Is there a way of calculating the average of the values of two or more lists or even dictionaries?
This is what I came up with:
lista = [1, 2, 3, 4, 5]
listb = [5, 4, 3, 2, 1]
listavg = [0]*5
count = 0
for i in lista:
listavg[count] = (i + listb[count]) / 2
count += 1
print(listavg)
[3.0, 3.0, 3.0, 3.0, 3.0]
But what if I have 100 lists? And what if those lists are inside dictionaries like these:
{'A': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'B': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'C': [2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 'D': [3, 3, 3, 3, 3, 3, 3, 3, 3, 3], 'E': [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], 'F': [5, 5, 5, 5, 5, 5, 5, 5, 5, 5], 'G': [6, 6, 6, 6, 6, 6, 6, 6, 6, 6], 'H': [7, 7, 7, 7, 7, 7, 7, 7, 7, 7], 'I': [8, 8, 8, 8, 8, 8, 8, 8, 8, 8], 'J': [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]}
P.S. the length of the list is always the same.
EDIT: Important note is that I want the average of each index, not the average of the list.
Upvotes: 1
Views: 131
Reputation: 43146
Use zip and a list comprehension:
>>> [sum(l)/len(l) for l in zip(*list_dict.values())]
[4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5]
Upvotes: 4
Reputation: 152
lista = [1, 2, 3, 4]
listb = [5, 6, 7, 8, 9]
lists = lista + listb
average = sum(lists) / len(lists)
I think this works fine.
Upvotes: 0
Reputation: 22953
You can use zip()
to get a tuple of each element grouped together index-wise from the input lists, and use sum()
to add them together:
>>> def averages(*lists):
return [sum(els) / len(els) for els in zip(*lists)]
>>> averages([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])
[3.0, 3.0, 3.0, 3.0, 3.0]
>>>
Upvotes: 1