How would I sum a multi-dimensional array in the most succinct python?

后端 未结 3 1010
孤城傲影
孤城傲影 2020-12-19 01:33

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,         


        
相关标签:
3条回答
  • 2020-12-19 01:55

    Another solution using itertools:

    >>> from itertools import chain
    >>> my_list = [ [1,2,3,4], [2,4,5,6] ]
    >>> sum(chain(*my_list))
    27
    
    0 讨论(0)
  • 2020-12-19 02:05

    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.

    0 讨论(0)
  • 2020-12-19 02:08
    >>> sum ( [ sum(x) for x in [[1,2,3,4], [2,4,5,6]] ] )
    27
    
    0 讨论(0)
提交回复
热议问题