[英]How do I print/return the sum of all values in a matrix in Python?
I need to create a function which takes a matrix as an argument and then returns the sum of all the values in the matrix.我需要创建一个 function,它将矩阵作为参数,然后返回矩阵中所有值的总和。 So if the matrix passed to the function was = [[12, 4], [9, 6], [5, 7]] I want the function to return the value 43
因此,如果传递给 function 的矩阵 = [[12, 4], [9, 6], [5, 7]] 我希望 function 返回值 43
There are two ways.有两种方法。
(1) Use numpy. (1) 使用 numpy。
L = [[12, 4], [9, 6], [5, 7]]
np.array(L).sum()
(2) Use iteration. (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
Use itertools.chain.from_iterable()
to flatten the list, then call sum()
:使用
itertools.chain.from_iterable()
来展平列表,然后调用sum()
:
>>> from itertools import chain
>>> was = [[12, 4], [9, 6], [5, 7]]
>>> sum(chain.from_iterable(was))
43
Could also flatten this way:也可以这样展平:
>>> sum(number for sublst in was for number in sublst)
43
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.