遍历数组并对元素进行计算

时间:2019-01-22 06:00:26

标签: python numpy

我有一个数组,想要在迭代过程中求和特定元素。我很难找到一种使用循环执行此操作的方法。 数组形状为(25,25)

array 
  [ 92843,  86851,  91950,  98232,  83329,  94591,  88962,  97020,
        107113,  98452, 103242, 106442, 123032, 119063, 112971, 114715,
        108654, 114856, 109872, 124583, 120518, 112815, 120780, 127831,
        147174],
       [132633, 124073, 131357, 140331, 119041, 135131, 127089, 138601,
        153019, 140647, 147489, 152061, 175761, 170090, 161388, 163879,
        155221, 164080, 156960, 177976, 172169, 161165, 172544, 182617,
        210249],
       [159159, 148887, 157629, 168397, 142849, 162157, 152507, 166321,
        183623, 168776, 176986, 182473, 210913, 204108, 193665, 196655,
        186265, 196896, 188352, 213571, 206602, 193398, 207052, 219140,
        252298]

我想为每次迭代打印出如下结果

print(array[23][0]+array[23][1]) # 159159 + 148887 = 308046
print(array[22][0]+array[22][1]+array[22][2]) #132633 + 124073 + 131357 = 388063
print(array[21][0]+array[21][1]+array[21][2]+array[21][3]) # 92843 +  86851 + 91950 + 98232 = 369876 

将每个元素表示为array[i][j],如您在每次迭代i-1中所见,并且j的“长度”增加了一个。
无论如何,我可以使用循环执行此任务吗?谢谢!

3 个答案:

答案 0 :(得分:4)

尝试一下:

for i, sub in enumerate(reversed(array)):
    print(sum(sub[:i]))

例如,如果

array = [[ 1,  2,  3,  4,  5],
         [ 6,  7,  8,  9, 10],
         [11, 12, 13, 14, 15],
         [16, 17, 18, 19, 20],
         [21, 22, 23, 24, 25]]

输出应为

0    # last row, no elements summed
16   # 16 = 16
23   # 11 + 12 = 23
21   # 6 + 7 + 8 = 21
10   # 1 + 2 + 3 + 4 = 10

答案 1 :(得分:3)

您可能只需要np.tril,然后是np.sum(_, axis=0)。这将得出lower triangle of the matrix每一行的总和。如果您需要的话,可以轻松地更改以提供上三角。

print(np.sum(np.tril(array), axis=0))

答案 2 :(得分:1)

In [661]: arr = np.arange(1,17).reshape(4,4)
In [662]: arr
Out[662]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])

In [666]: for i in range(3,-1,-1):
     ...:     c = arr[i,:4-i]
     ...:     print(c.sum(), c)
     ...:     
13 [13]
19 [ 9 10]
18 [5 6 7]
10 [1 2 3 4]