有没有一种简单的方法可以在 python 中计算 N 个列表的元素总和?我知道如果我们有 n 个列表 defined(调用第 i 个列表 c_i
),我们可以:
z = [sum(x) for x in zip(c_1, c_2, ...)]
例如:
c1 = [1,2]
c2 = [3,4]
c3 = [5,6]
z = [sum(x) for x in zip(c1,c2,c3)]
此处 z = [9, 12]
但是如果我们没有定义 c_i
而是在列表 C
中有 c_1...c_n
怎么办?
如果我们只有 C
,是否有类似的方法找到 z
?
我希望这是清楚的。
已解决:我想知道 * 运算符是什么意思...谢谢!
最佳答案
只需这样做:
[sum(x) for x in zip(*C)]
在上面,C
是c_1...c_n
的列表。如 link 中所述在评论中(感谢@kevinsa5!):
*
is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call.
有关更多详细信息,请查看 documentation ,在“解包参数列表”下,还阅读了关于 calls 的内容(谢谢,@abarnert!)
关于python - N 列表的总和元素明智的 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19261747/