問題描述
有沒有一種簡單的方法來計算 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)]
在上面,C
是c_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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!