Python:部分数字和

时间:2012-11-04 19:13:51

标签: python

你可以帮助我使用返回文本文件中部分数字总和的代码吗? 我必须导入文本文件,然后在没有工具的情况下为部分总和制作代码..等等。

我的意见:

4
13
23
21
11

输出应该是(不带括号或逗号):

4 
17
40
61 
72

我试图在python中创建代码,但只能做总和而不是部分。 如果我使用+=运算符作为生成器,它会给我一个错误!

7 个答案:

答案 0 :(得分:13)

好吧,因为每个人似乎都在为解决问题提供他们最喜欢的习惯用法,所以Python 3中的itertools.accumulate如何:

>>> import itertools
>>> nums = [4, 13, 23, 21, 11]
>>> list(itertools.accumulate(nums))
[4, 17, 40, 61, 72]

答案 1 :(得分:12)

有许多方法可以创建部分和的序列。我认为最优雅的是使用generator

def partial_sums(iterable):
    total = 0
    for i in iterable:
        total += i
        yield total

您可以像这样运行:

nums = [4, 13, 23, 21, 11]
sums = list(partial_sums(nums)) # [ 4, 17, 40, 61, 72]

编辑要从文件中读取数据值,您可以使用其他生成器,并将它们链接在一起。以下是我的表现:

with open("filename.in") as f_in:
    # Sums generator that "feeds" from a generator expression that reads the file
    sums = partial_sums(int(line) for line in f_in)

    # Do output:
    for value in sums:
        print(value)

    # If you need to write to a file, comment the loop above and uncomment this:
    # with open("filename.out", "w") as f_out:
    #    f_out.writelines("%d\n" % value for value in sums)

答案 2 :(得分:3)

numpy.cumsum会做你想做的事。

如果您没有使用numpy,则可以自行编写。

def cumsum(i):
    s = 0
    for elt in i:
        s += elt
        yield s

答案 3 :(得分:2)

类似的东西:

>>> lis=[4, 13, 23, 21 ,11]
>>> [sum(lis[:i+1]) for i,x in enumerate(lis)]
[4, 17, 40, 61, 72]

答案 4 :(得分:2)

试试这个:

import numpy as np

input = [ 4, 13, 23, 21, 11 ]
output = []
output.append(input[0])
for i in np.arange(1,len(input)):
    output.append(input[i] + input[i-1])

print output

答案 5 :(得分:2)

在numpy中使用累积总和:

import numpy as np
input = np.array([4, 13, 23, 21 ,11])
output = input.cumsum()

结果:

print output
>>>array([ 4, 17, 40, 61, 72])

或者,如果您需要列表,可以将输出转换为列表:

output = list(output)
print output
>>>[4, 17, 40, 61, 72]

答案 6 :(得分:1)

这是使用reduce的替代解决方案:

nums = [4, 13, 23, 21, 11]
partial_sum = lambda a, b: a + [a[-1] + b]
sums = reduce(partial_sum, nums[1:], nums[0:1])

lambda中的加号不是同一个运算符,第一个是列表连接,第二个是两个整数的和。 Altough Blckknght可能更清楚,这个更短,适用于Python 2.7。