N个列表元素的总和python

2022-11-05Python开发问题
5

本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10