N个列表元素的总和python

sum of N lists element-wise python(N个列表元素的总和python)
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)