N的总和列出按元素排列的python [英] sum of N lists element-wise python

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

问题描述

是否有一种简单的方法来计算python中N个列表的元素方式总和?我知道如果我们有n个定义为 的列表(称为ith列表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天全站免登陆