如何在最简洁的python中求和多维数组? [英] How would I sum a multi-dimensional array in the most succinct python?
问题描述
与之最接近的是求和列
所以我会在我的问题中做类似的事情:
So I'll do something similar in my question:
说我有一个Python 2D列表,如下所示:
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 ]
在一行中,我如何求和整个2d数组?
In one line, how can I sum the entire 2d-array?
27
推荐答案
您可以轻松完成
sum(map(sum, my_list))
或者
sum(sum(x) for x in my_list))
并称其为一日,如果您不希望超过2个维度.请注意,由于使用了map()
,第一个解决方案很可能不是最快的解决方案(与执行时间一样).进行基准测试并根据需要进行比较.
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.
最后,如果您发现自己使用了多维数组,请考虑使用 NumPy 及其出色的数组友好功能.这是您的问题的简短摘录:
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.
这篇关于如何在最简洁的python中求和多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!