部分和のシーケンスを作成するには、いくつかの方法があります。最もエレガントなのは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)
は、あなたがしたいですか配列の結果、または単に印刷された出力? – BobS
以下のようになります: 'reduce(lambda c、x:c + [c [-1] + x]、[4,13,23,21,11]、[0])[1:]' –