Is there an easy way to compute the element-wise sum of N lists in python? I know if we have n lists defined (call the ith list c_i
), we can do:
z = [sum(x) for x in zip(c_1, c_2, ...)]
For example:
c1 = [1,2]
c2 = [3,4]
c3 = [5,6]
z = [sum(x) for x in zip(c1,c2,c3)]
Here z = [9, 12]
But what if we don't have c_i
defined and instead have c_1...c_n
in a list C
?
Is there a similar way to find z
if we just have C
?
I hope this is clear.
resolved: I was wondering what the * operator was all about...thanks!
This isn't all that different from Óscar López's answer, but uses
itertools.imap
instead of a list comprehension.Just do this:
In the above,
C
is the list ofc_1...c_n
. As explained in the link in the comments (thanks, @kevinsa5!):For additional details, take a look at the documentation, under "unpacking argument lists" and also read about calls (thanks, @abarnert!)