【问题标题】:How do I perform a cumulative sum on groups of numbers in a list?如何对列表中的数字组执行累积求和?
【发布时间】:2021-09-10 17:46:19
【问题描述】:

问题:如何补全和简化下面的语法以达到想要的输出?

期望的输出:

[16.0, 22.0, 26.0, 15.0, 18.0, 21.0, 5.0, 6.0, 8.0]

当前语法:

a = [16.0, 6.0, 4.0, 15.0, 3.0, 3.0, 5.0, 1.0, 2.0]  #---> there is 3 sets of data in here, 
                                                           assuming the number of sets will 
                                                           change at different point in time

 b = 3    #----> this represents the number of dataset in "a", and will to change at different   
                 point in time

c = []

for idx, i in enumerate(a[0:3]):
    if idx == 0:
        c.append(i)
    else:
        c.append(a[idx-1] + i)

for idx, i in enumerate(a[3:6]):
    if idx == 0:
        c.append(i)
    else:
        c.append(a[idx-1] + i)        

for idx, i in enumerate(a[6:9]):
    if idx == 0:
        c.append(i)
    else:
        c.append(a[idx-1] + i) 
        
print(c)

【问题讨论】:

  • 你是在问如何计算给定b = 3的数字0、3、6、9?
  • @mkrieger1 OP 想要三个一组的累积总和。
  • @DreamyDeerz 您是否得到了任何一个已发布答案的帮助?如果是这样,请投票并将其标记为正确,以便可以从未答复队列中删除此帖子。

标签: python python-3.x for-loop


【解决方案1】:

如果您不反对使用 numpy(强烈建议您随时使用数值数据):

>>> import numpy as np

>>> a = np.array([16.0, 6.0, 4.0, 15.0, 3.0, 3.0, 5.0, 1.0, 2.0])
>>> b = 3

>>> np.cumsum(a.reshape(-1, b), axis=1).flatten()
array([16., 22., 26., 15., 18., 21.,  5.,  6.,  8.])

当然,这假设a 可以均匀地分解成b 大小的块。

步骤

重塑成行,其中每一行是 b 项目数的子组(-1 告诉 numpy 确定需要多少行):

>>> a.reshape(-1, b)
array([[16.,  6.,  4.],
       [15.,  3.,  3.],
       [ 5.,  1.,  2.]])

每行累计:

np.cumsum(a.reshape(-1, b), axis=1)
array([[16., 22., 26.],
       [15., 18., 21.],
       [ 5.,  6.,  8.]])

展平成一个列表:

>>> np.cumsum(a.reshape(-1, b), axis=1).flatten()
array([16., 22., 26., 15., 18., 21.,  5.,  6.,  8.])

【讨论】:

    【解决方案2】:

    使用range() 中的step 参数一次移动b 步骤,在这种情况下,我们将得到索引(0, 3, 6)。然后,对于每个索引,使用另一个 for 循环来执行累积和。代码如下:

    a = [16.0, 6.0, 4.0, 15.0, 3.0, 3.0, 5.0, 1.0, 2.0]
    b = 3
    c = []
    for i in range(0, len(a), b):
        total = 0
        for j in range(b):
            total += a[i + j]
            c.append(total)
    
    print(c)
    

    输出:

    [16.0, 22.0, 26.0, 15.0, 18.0, 21.0, 5.0, 6.0, 8.0]
    

    【讨论】:

      猜你喜欢
      • 2013-05-08
      • 1970-01-01
      • 2013-03-31
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 2023-01-20
      • 2016-07-23
      相关资源
      最近更新 更多