簡體   English   中英

如何打印/返回 Python 中矩陣中所有值的總和?

[英]How do I print/return the sum of all values in a matrix in Python?

我需要創建一個 function,它將矩陣作為參數,然后返回矩陣中所有值的總和。 因此,如果傳遞給 function 的矩陣 = [[12, 4], [9, 6], [5, 7]] 我希望 function 返回值 43

有兩種方法。

(1) 使用 numpy。

L = [[12, 4], [9, 6], [5, 7]]
np.array(L).sum()

(2) 使用迭代。

L = [[12, 4], [9, 6], [5, 7]]
sum([sum(l) for l in L])
Was = [[12, 4], [9, 6], [5, 7]]
>>> count = 0
>>> for i in was:
...     for j in i:
...             count += j
... 
>>> count
43

使用map()

sum(map(sum,[[12, 4], [9, 6], [5, 7]]))

使用itertools.chain.from_iterable()來展平列表,然后調用sum()

>>> from itertools import chain
>>> was = [[12, 4], [9, 6], [5, 7]]
>>> sum(chain.from_iterable(was))
43

也可以這樣展平:

>>> sum(number for sublst in was for number in sublst)
43

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM