【问题标题】:Sum consecutive numbers in a list. Python对列表中的连续数字求和。 Python
【发布时间】:2013-06-12 20:39:36
【问题描述】:

我正在尝试对列表中的连续数字求和,同时保持第一个相同。

所以在这种情况下,5 将保持 5,10 将是 10 + 5 (15),15 将是 15 + 10 + 5 (30)

x = [5,10,15]
y = []

for value in x:
   y.append(...)

print y

[5,15,30]

【问题讨论】:

  • 你能改变接受的答案吗?

标签: python function numbers sum


【解决方案1】:

你想要itertools.accumulate()(在 Python 3.2 中添加)。不需要额外的东西,已经为您实现了。

在不存在此功能的早期 Python 版本中,您可以使用给定的纯 python 实现:

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total

这将完美地与任何可迭代、懒惰和高效的工作。 itertools 实现是在较低级别实现的,因此速度更快。

如果你想要它作为一个列表,那么自然只需使用内置的list()list(accumulate(x))

【讨论】:

    【解决方案2】:
    y = [sum(x[:i+1]) for i in range(len(x))]
    

    【讨论】:

    • 这需要创建大量子列表,并且仅适用于序列,而不适用于任意迭代。它还在 3.2+ 中重新发明轮子。
    • @draconisthe0ry:请注意这种方法的性能特征,因为当列表很长时它会变得很慢。它不仅创建len(x) 子列表,而且每次都会对每个子列表求和,而不是将最新值添加到运行总和中。 Lattyware 的答案是 pythonic 解决方案。
    【解决方案3】:

    使用 numpy.cumsum:

    In[1]: import numpy as np
    In[2]: x = [5,10,15]
    In[3]: x = np.array(x)
    In[4]: y = x.cumsum()
    In[5]: y
    Out[6]: array([ 5, 15, 30])
    

    我正在使用 Python 3.4

    【讨论】:

      【解决方案4】:

      总之所有元素直到你所在的元素?

      x = [5,10,15]
      y = [sum(x[:i+1]) for i in range(len(x))]
      

      【讨论】:

      • 没有。这个是 [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] 。谢谢你
      猜你喜欢
      • 2019-02-23
      • 2021-01-28
      • 2016-08-26
      • 2020-02-19
      • 2019-10-25
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2019-06-30
      相关资源
      最近更新 更多