Question

In Python, we have a list of list. For example:

a1 = [[1,4,3,5,6],[6,7,5,3,12],[1,6,4,1,2],[1,9,4,2,1]]

or

a2 = [[4,3,5,6],[6,7,5,12],[1,6,4,2],[1,9,2,1],[3,2,5,11]]

Both the length of a and the length of inside lists may vary. But all inside list always have the same length.

I'd like to apply some function to all lists made of the n-th element of each list.

Considering a2 for example, I'd like to apply iteratively a function to the list [4,6,1,1,3] (list of first elements), then to the list [3,7,6,9,2] (list of the second elements), etc…

the idea resemble to the function:

map(a2, my_function)

Except that my_function should not be applied to each inside list but to each list of n-th elements.

Hope that makes sense!

What is most pythonic way for performing such thing?

Was it helpful?

Solution

Use zip with * operator:

>>> a1 = [[1,4,3,5,6],[6,7,5,3,12],[1,6,4,1,2],[1,9,4,2,1]]
>>> a2 = [[4,3,5,6],[6,7,5,12],[1,6,4,2],[1,9,2,1],[3,2,5,11]]

>>> zip(*a1)
[(1, 6, 1, 1), (4, 7, 6, 9), (3, 5, 4, 4), (5, 3, 1, 2), (6, 12, 2, 1)]
>>> zip(*a2)
[(4, 6, 1, 1, 3), (3, 7, 6, 9, 2), (5, 5, 4, 2, 5), (6, 12, 2, 1, 11)]

>>> map(sum, zip(*a1)) # [1+6+1+1, 4+7+6+9, ...]
[9, 26, 16, 11, 21]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top