Want to find a way of doing an average of multiple lists
10,463
Solution 1
Averages:
>>> data = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> from __future__ import division
>>> [sum(e)/len(e) for e in zip(*data)]
[1.3333333333333333, 3.0, 4.0]
Sums:
>>> data = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> [sum(e) for e in zip(*data)]
[4, 9, 12]
returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments ... write the function call with the *-operator to unpack the arguments out of a list or tuple.
>>> data
[[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> zip(*data)
[(1, 1, 2), (2, 3, 4), (3, 4, 5)]
Solution 2
>>> l = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> zip(*l)
[(1, 1, 2), (2, 3, 4), (3, 4, 5)]
>>> def average(nums, default=float('nan')):
... return sum(nums) / float(len(nums)) if nums else default
...
>>> [average(n) for n in zip(*l)]
[2.0, 2.6666666666666665, 3.6666666666666665]
Author by
user2175034
Updated on June 27, 2022Comments
-
user2175034 almost 2 years
Say we create a list like so in python:
[[1, 2, 3], [1, 3, 4], [2, 4, 5]]
And then I want to take
1+1+2
and divide by 3, giving me the average for that element and store in a new list. I want to do that again for the second elements and lastly for the third. How would one do it succinctly? (I cannot think of a way other than multiple loops.)The output should be a new list
[(1+1+2), (2+3+4), (3+4+5)]
Thanks so much!
-
abarnert about 11 yearsI think you want
zip(*l)
in your last line. Otherwise, you're just averaging each sublist (so you get 2, 2-2/3, and 3-2/3 instead of 1-1/3, 3, and 4).