【问题标题】:Python: Partial sum of numbers [duplicate]Python:数字的部分总和[重复]
【发布时间】:2012-11-04 19:13:51
【问题描述】:

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

我的意见:

4
13
23
21
11

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

4 
17
40
61 
72

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

【问题讨论】:

  • 你想要一个数组结果,还是只是打印输出?
  • 看:reduce(lambda c, x: c + [c[-1] + x], [4, 13, 23, 21, 11], [0])[1:]

标签: python


【解决方案1】:

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

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

【讨论】:

  • 注意:“3.2 版中的新功能”。有趣的补充。 :)
  • @hayden:在 3.3 中更好。 3.2 不接受函数参数。
  • 我特别喜欢total = next(it) 处理[] 案例的方式...
  • 哇,我不知道他们会添加这个。太糟糕了,3.3 版本将 func 作为 second 参数——我希望它们与 mapreduce 一致(以及几乎所有其他接受函数的 itertools 函数作为参数)。
  • 它应该是打印输出(不带括号),并且由于某些对我来说未知的原因,我无法导入 itertools。可以用其他方法吗?
【解决方案2】:

numpy.cumsum 会做你想做的事。

如果你不使用numpy,你可以自己写。

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

【讨论】:

  • 我不认为添加对 numpy 的依赖是一个好主意,除非他已经在使用它。
【解决方案3】:

有多种方法可以创建部分和的序列。我认为最优雅的是使用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)

【讨论】:

  • 这可能是 OP 最有用的答案。
  • 做到了!谢谢好心的先生!
  • @user1798558:如果这个答案对您有所帮助,您可以通过选择左侧的绿色复选标记来感谢作者(有关说明,请参阅here。)
【解决方案4】:

在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]

【讨论】:

    【解决方案5】:

    这是使用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。

    【讨论】:

      【解决方案6】:

      类似这样的:

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

      【讨论】:

      • -1 这会计算 sum([4]),然后是 sum([4,13]),然后是 sum([4,13,23]),等等 - 打败了累积和的点!
      • 我不会说它违背了目的。这是一种低效的计算方式(O(n^2) 而不是 O(n)),但它得到了正确的答案。
      【解决方案7】:

      试试这个:

      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
      

      【讨论】:

        猜你喜欢
        • 2020-01-06
        • 2020-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 2021-02-21
        相关资源
        最近更新 更多