How would I sum a multi-dimensional array in the m

2019-01-27 17:54发布

The closest was this one summing columns.

So I'll do something similar in my question:

Say I've a Python 2D list as below:

my_list =  [ [1,2,3,4],
             [2,4,5,6] ]

I can get the row totals with a list comprehension:

row_totals = [ sum(x) for x in my_list ]

In one line, how can I sum the entire 2d-array?

27

5条回答
爷的心禁止访问
2楼-- · 2019-01-27 18:29

You can do as easy as

sum(map(sum, my_list))

or alternatively

sum(sum(x) for x in my_list))

and call it a day, if you don't expect more than 2 dimensions. Note that the first solution is most likely not the fastest (as in execution time) solution, due to the usage of map(). Benchmark and compare as necessary.

Finally, if you find yourself using multidimensional arrays, consider using NumPy and its superior array-friendly functions. Here's a short excerpt for your problem:

import numpy as np

my_list = np.array([[1,2,3,4], [2,4,5,6]])
np.sum(my_list)

This would work for any number of dimensions your arrays might have.

查看更多
我只想做你的唯一
3楼-- · 2019-01-27 18:38
>>> sum ( [ sum(x) for x in [[1,2,3,4], [2,4,5,6]] ] )
27
查看更多
狗以群分
4楼-- · 2019-01-27 18:41

Another solution using itertools:

>>> from itertools import chain
>>> my_list = [ [1,2,3,4], [2,4,5,6] ]
>>> sum(chain(*my_list))
27
查看更多
时光不老,我们不散
5楼-- · 2019-01-27 18:47
>>> from itertools import chain
>>> my_list = [[1,2,3,4], [2,4,5,6]]
>>> sum(chain.from_iterable(my_list))
27
查看更多
女痞
6楼-- · 2019-01-27 18:53

You can use sum to first add the inner lists together and then sum the resulting flattened list:

>>> my_list = [ [1,2,3,4], [2,4,5,6] ]

>>> sum(my_list, [])
[1, 2, 3, 4, 2, 4, 5, 6]

>>> sum(sum(my_list, []))
27
查看更多
登录 后发表回答