【问题标题】:Summed area table without module python 3没有模块python 3的总面积表
【发布时间】:2019-03-31 18:23:10
【问题描述】:

任何人都知道是否有一种方法可以在没有模块的情况下创建总面积表(SAT)? 我已经尝试过这个并工作了:

import numpy as np

A = np.random.randint(0, 10, (3, 4))

print (A)
print(A.cumsum(axis=0).cumsum(axis=1))

但这是使用模块 numpy。

【问题讨论】:

标签: python numpy sum


【解决方案1】:
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)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2013-01-06
    • 1970-01-01
    • 2013-01-03
    • 2012-12-14
    相关资源
    最近更新 更多