[英]sum of N lists element-wise python
Is there an easy way to compute the element-wise sum of N lists in python? 有没有一种简单的方法来计算python中N个列表的元素总和? I know if we have n lists defined (call the ith list c_i
), we can do: 我知道如果我们定义了 n个列表(调用第i个列表c_i
),我们可以这样做:
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]
这里z = [9, 12]
But what if we don't have c_i
defined and instead have c_1...c_n
in a list C
? 但是如果我们没有定义c_i
而在列表C
有c_1...c_n
呢?
Is there a similar way to find z
if we just have C
? 如果我们只有C
是否有类似的方法来找到z
?
I hope this is clear. 我希望这很清楚。
resolved: I was wondering what the * operator was all about...thanks! 已解决:我想知道*运营商的全部内容......谢谢!
Just do this: 这样做:
[sum(x) for x in zip(*C)]
In the above, C
is the list of c_1...c_n
. 在上面, C
是c_1...c_n
的列表。 As explained in the link in the comments (thanks, @kevinsa5!): 正如评论中的链接所解释的那样(谢谢,@ kevinsa5!):
*
is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call.*
是“splat”运算符:它将列表作为输入,并将其扩展为函数调用中的实际位置参数。
For additional details, take a look at the documentation , under "unpacking argument lists" and also read about calls (thanks, @abarnert!) 有关其他详细信息,请查看“解压缩参数列表”下的文档 ,并阅读有关调用的信息 (谢谢,@ abarnert!)
This isn't all that different from Óscar López's answer, but uses itertools.imap
instead of a list comprehension. 这与ÓscarLópez的答案没有什么不同,但使用itertools.imap
而不是列表理解。
from itertools import imap
list(imap(sum, zip(*C))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.