Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 986
user2175034 Avatar asked Apr 23 '13 00:04

user2175034


Video Answer


2 Answers

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]

  • zip

returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

  • Unpacking argument lists

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)]
like image 154
Pavel Anossov Avatar answered Nov 09 '22 22:11

Pavel Anossov


>>> 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]
like image 43
John Kugelman Avatar answered Nov 09 '22 22:11

John Kugelman