user2175034
user2175034

Reputation: 93

Want to find a way of doing an average of multiple lists

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!

Upvotes: 6

Views: 11405

Answers (2)

John Kugelman
John Kugelman

Reputation: 361564

>>> 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]

Upvotes: 1

Pavel Anossov
Pavel Anossov

Reputation: 62868

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)]

Upvotes: 14

Related Questions