Python:部分数字和

use*_*558 6 python

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

我的意见:

4
13
23
21
11
Run Code Online (Sandbox Code Playgroud)

输出应该是(没有括号或逗号):

4 
17
40
61 
72
Run Code Online (Sandbox Code Playgroud)

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

DSM*_*DSM 14

好吧,因为每个人似乎都在为解决这个问题提供他们最喜欢的习语,所以Python 3中的itertools.accumulate怎么样:

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

  • @hayden:在3.3中更好.3.2不接受函数参数. (2认同)

Blc*_*ght 12

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

def partial_sums(iterable):
    total = 0
    for i in iterable:
        total += i
        yield total
Run Code Online (Sandbox Code Playgroud)

你可以像这样运行它:

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

编辑要从文件中读取数据值,您可以使用另一个生成器,并将它们链接在一起.这是我如何做到的:

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)
Run Code Online (Sandbox Code Playgroud)


Kat*_*iel 5

numpy.cumsum 会做你想做的。

如果您不使用numpy,则可以编写自己的。

def cumsum(i):
    s = 0
    for elt in i:
        s += elt
        yield s
Run Code Online (Sandbox Code Playgroud)

  • 我不认为添加对 numpy 的依赖是一个好主意,除非他已经在使用它。 (4认同)

Ash*_*ary 1

像这样的东西:

>>> lst = [4, 13, 23, 21 ,11]
>>> [sum(lst[:i+1]) for i, x in enumerate(lst)]
[4, 17, 40, 61, 72]
Run Code Online (Sandbox Code Playgroud)

  • 我不会说这违背了目的。这是一种低效的计算方法(O(n^2) 而不是 O(n)),但它得到了正确的答案。 (7认同)
  • -1 这会计算“sum([4])”,然后是“sum([4,13])”,然后是“sum([4,13,23])”,等等——破坏了求累积和的点! (6认同)