任何人都知道是否有一种无需模块即可创建总面积表(SAT)的方法吗? 我已经尝试过并工作:
import numpy as np
A = np.random.randint(0, 10, (3, 4))
print (A)
print(A.cumsum(axis=0).cumsum(axis=1))
但这是与numpy模块一起使用的。
答案 0 :(得分:0)
In [99]: A = np.random.randint(0, 10, (3, 4))
In [100]: A
Out[100]:
array([[1, 4, 0, 9],
[5, 5, 3, 0],
[3, 2, 1, 2]])
In [101]: A.cumsum(axis=0).cumsum(axis=1)
Out[101]:
array([[ 1, 5, 5, 14],
[ 6, 15, 18, 27],
[ 9, 20, 24, 35]])
itertools
有一个accumulate
工具,其行为类似于cumsum
:
https://docs.python.org/3/library/itertools.html#itertool-functions
In [102]: from itertools import accumulate
In [103]: Al = A.tolist()
In [105]: [list(accumulate(row)) for row in Al]
Out[105]: [[1, 5, 5, 14], [5, 10, 13, 13], [3, 5, 6, 8]]
In [106]: [list(accumulate(row)) for row in zip(*_)]
Out[106]: [[1, 6, 9], [5, 15, 20], [5, 18, 24], [14, 27, 35]]
In [107]: list(zip(*_))
Out[107]: [(1, 5, 5, 14), (6, 15, 18, 27), (9, 20, 24, 35)]
或打包成一个表达式:
In [109]: list(zip(*
...: (accumulate(row) for row in zip(*
...: (accumulate(row) for row in Al)))))
...:
Out[109]: [(1, 5, 5, 14), (6, 15, 18, 27), (9, 20, 24, 35)]
如果您也不能使用itertools
,请使用文档页面上提供的rough equivalent
生成器。
或者具有这种小的累加功能:
def accum(alist):
total = 0; res = []
for a in alist:
total += a
res.append(total)
return res
In [111]: list(zip(*
...: (accum(row) for row in zip(*
...: (accum(row) for row in Al)))))
Out[111]: [(1, 5, 5, 14), (6, 15, 18, 27), (9, 20, 24, 35)]