N个列表元素的总和python [英] sum of N lists element-wise python

查看:33
本文介绍了N个列表元素的总和python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来计算 Python 中 N 个列表的元素总和?我知道如果我们有n个列表定义(调用第i个列表c_i),我们可以这样做:

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, ...)]

例如:

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 怎么办?

But what if we don't have c_i defined and instead have c_1...c_n in a list C?

如果我们只有 C,有没有类似的方法可以找到 z?

Is there a similar way to find z if we just have C?

我希望这很清楚.

已解决:我想知道 * 运算符是什么意思...谢谢!

resolved: I was wondering what the * operator was all about...thanks!

推荐答案

这样做:

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

在上面,Cc_1...c_n的列表.正如评论中的 链接 中所述(感谢@kevinsa5!):

In the above, C is the list of c_1...c_n. As explained in the link in the comments (thanks, @kevinsa5!):

* 是splat"运算符:它将一个列表作为输入,并将其扩展为函数调用中的实际位置参数.

* is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call.

有关更多详细信息,请查看 文档,在解包参数列表"下,还阅读了有关 调用 (谢谢@abarnert!)

For additional details, take a look at the documentation, under "unpacking argument lists" and also read about calls (thanks, @abarnert!)

这篇关于N个列表元素的总和python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆