N个列表元素的总和python

2024-05-16 06:40:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,有没有一种简单的方法来计算N个列表的元素和?我知道如果我们定义了n个list(调用第I个listc_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

我希望这是清楚的。

解决:我想知道接线员是怎么回事…谢谢!


Tags: 方法in元素列表for定义ziplist
2条回答

就这样做:

[sum(x) for x in zip(*C)]

在上面,Cc_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!)

这与斯卡·洛佩兹的答案并没有太大区别,而是使用itertools.imap而不是列表理解。

from itertools import imap
list(imap(sum, zip(*C))

相关问题 更多 >