简体   繁体   中英

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. So if the matrix passed to the function was = [[12, 4], [9, 6], [5, 7]] I want the function to return the value 43

There are two ways.

(1) Use numpy.

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

(2) Use iteration.

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

Using map()

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

Use itertools.chain.from_iterable() to flatten the list, then call 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM