9

你能帮我处理在文本文件中返回部分数字总和的代码吗?我必须导入文本文件,然后在没有工具的情况下为部分总和编写代码..etc。

我的输入:

4
13
23
21
11

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

4 
17
40
61 
72

我试图用python编写代码,但只能做总和而不是部分。如果我将+=运算符用于生成器,它会给我一个错误!

4

7 回答 7

22

好吧,既然每个人似乎都在用他们最喜欢的习语来解决问题,那么Python 3 中的itertools.accumulate怎么样:

>>> import itertools
>>> nums = [4, 13, 23, 21, 11]
>>> list(itertools.accumulate(nums))
[4, 17, 40, 61, 72]
于 2012-11-04T19:23:46.957 回答
13

There are a number of ways to create your sequence of partial sums. I think the most elegant is to use a generator.

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

You can run it like this:

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

Edit To read the data values from your file, you can use another generator, and chain them together. Here's how I'd do it:

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)
于 2012-11-04T19:20:18.967 回答
5

numpy.cumsum will do what you want.

If you're not using numpy, you can write your own.

def cumsum(i):
    s = 0
    for elt in i:
        s += elt
        yield s
于 2012-11-04T19:17:15.317 回答
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]
于 2014-07-31T20:53:43.757 回答
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
于 2012-11-04T19:23:42.167 回答
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 中的加号不是同一个运算符,第一个是列表连接,第二个是两个整数的和。虽然 Blckknght 可能更清楚,但这个更短并且适用于 Python 2.7。

于 2014-07-31T20:40:26.100 回答
1

something like this:

>>> lst = [4, 13, 23, 21 ,11]
>>> [sum(lst[:i+1]) for i, x in enumerate(lst)]
[4, 17, 40, 61, 72]
于 2012-11-04T19:16:55.143 回答