Python Forum

Full Version: Unpacking nested lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey, I beleive it's a relatively simple quiestion although i didn't find any simple answer in Google.

I'd like to create a function that unpacks a list of lists and create a new list that sums up the variables which are in the same index.
For instance: [[1,1],[1,3]] ---> [2,4]

or [[1,1,1],[1,0,0],[0,0,100]] ---> [2,1,101]

Not suppose to be very complex.

Thanks!
>>> foo = [[1,1],[1,3]] 
>>> [sum(item) for item in zip(*foo)]
[2, 4]
>>> foo = [[1,1,1],[1,0,0],[0,0,100]]
>>> [sum(item) for item in zip(*foo)]
[2, 1, 101]
an alternative to list comprehension is map
>>> foo = [[1,1,1],[1,0,0],[0,0,100]]
>>> list(map(sum, zip(*foo)))
[2, 1, 101]