可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
can you help me with code which returns partial sum of numbers in text file? I must import text file, then make a code for partial sums without tools ..etc.
My input:
4 13 23 21 11
The output should be (without brackets or commas):
4 17 40 61 72
I was trying to make code in python, but could only do total sum and not partial one. If i use the +=
operator for generator, it gives me an error!
回答1:
Well, since everyone seems to be giving their favourite idiom for solving the problem, how about itertools.accumulate in Python 3:
>>> import itertools >>> nums = [4, 13, 23, 21, 11] >>> list(itertools.accumulate(nums)) [4, 17, 40, 61, 72]
回答2:
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)
回答3:
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
回答4:
something like this:
>>> lis=[4, 13, 23, 21 ,11] >>> [sum(lis[:i+1]) for i,x in enumerate(lis)] [4, 17, 40, 61, 72]
回答5:
try this:
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
回答6:
Use cumulative sum in numpy:
import numpy as np input = np.array([4, 13, 23, 21 ,11]) output = input.cumsum()
Result:
print output >>>array([ 4, 17, 40, 61, 72])
Or if you need a list, you may convert output to list:
output = list(output) print output >>>[4, 17, 40, 61, 72]
回答7:
This is an alternative solution using 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])
Pluses in lambda are not the same operator, the first one is list concatenation and the second one is sum of two integers. Altough Blckknght's may be more clear, this one is shorter and works in Python 2.7.