1

有没有更 Pythonic 的方式来执行以下操作?

total = 0
for index, value in enumerate(frequencies):
    total += value
    frequencies[index] = total
4

4 回答 4

4

对于 Python 3,使用itertools.accumulate

frequencies = list(itertools.accumulate(frequencies))

您的代码可能与 Pythonic 一样。人们很容易理解它的作用。

于 2013-10-02T12:07:00.873 回答
1

在 Python 2.x 上,您可以使用生成器函数(请注意,这会返回一个新列表):

def accumulate(lis):
    total = 0
    for item in lis:
        total += item
        yield total


>>> list(accumulate(range(5)))
[0, 1, 3, 6, 10]

在 Python 3.x 上使用itertools.accumulate.

于 2013-10-02T12:11:58.963 回答
1

我没有看到你写的任何非pythonic的东西。另一种可能是numpy.cumsum()

>>> 
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.cumsum()
array([ 0,  1,  3,  6, 10, 15, 21, 28, 36, 45])
>>> 
于 2013-10-02T12:38:37.067 回答
0

这是一个就地版本,如果您使用的是 python 2.x,这正是您正在寻找的版本。

frequencies = [1, 2, 3]
for i in range(1, len(frequencies)): frequencies[i] += frequencies[i - 1]
print frequencies

输出

[1, 3, 6]
于 2013-10-02T13:01:36.807 回答