Reputation: 223
I have a nested list in python, i=[[1,2,3],[4,5,6]]
. I want to sum the terms such that the final result is j=[1+4,2+5,6+3]
. I have tried:
i=[[1,2,3],[4,5,6]]
j=[sum(x) for x in zip(i)]
But this is what I get instead:
>>>print j
[6, 15]
Upvotes: 2
Views: 592
Reputation: 9753
zip
does not take a list
of list
s as an argument. It takes an arbitrary long list of list
arguments.
Here is how to do it:
i=[[1,2,3],[4,5,6]]
j=[sum(x) for x in zip(*i)]
Upvotes: 2
Reputation: 7592
You forgot the *
>>> i=[[1,2,3],[4,5,6]]
>>> [sum(x) for x in zip(*i)]
[5, 7, 9]
Upvotes: 1