各行にスペースで区切られた 2 つの値を含む txt ファイルがあります。
x1 y1
x2 y2
x3 y3
...
xn yn
以下を含む別のファイルを取得したい:
x1 y1
x2 y1+y2
x3 y1+y2+y3
...
xn y1+y2+y3+...+yn
python でこれを行うための最も速い(つまり最も簡単な)方法は何ですか?
各行にスペースで区切られた 2 つの値を含む txt ファイルがあります。
x1 y1
x2 y2
x3 y3
...
xn yn
以下を含む別のファイルを取得したい:
x1 y1
x2 y1+y2
x3 y1+y2+y3
...
xn y1+y2+y3+...+yn
python でこれを行うための最も速い(つまり最も簡単な)方法は何ですか?
これで始められます。
与えられたdata.txt
:
1 1
2 2
3 3
4 4
およびこのコード スニペット:
with open('data.txt') as inf:
ysum = 0
for line in inf:
line = line.split()
x, y = [float(i) for i in line]
ysum += y
print x, ysum
(上記を使用して)あなたに与えますfloat()
:
1.0 1.0
2.0 3.0
3.0 6.0
4.0 10.0
一方、次の行が必要な場合+
:
with open('data.txt') as inf:
yline = []
for line in inf:
line = line.split()
x = int(line[0])
yline = '+'.join(yline + [(line[1])])
print x, yline
yline = [yline]
int()
(この時間を使用して)あなたに与えます:
1 1
2 1+2
3 1+2+3
4 1+2+3+4
上記のコード、特に 2 番目のコードは、おそらくもっと合理化/最適化される可能性があると思いますが、始めるには十分なはずです。
文字列から適切な型 (float
またはint
) への変換を調整し、出力ファイルを作成して、好みの形式で書き込む必要があります。これらは、あなたが最もよく決めることができる詳細です。
コードに関して最も簡単な方法は、すでに配列numpy.cumsum()
を使用している場合です。numpy
import numpy as np
a = np.loadtxt("input.txt")
a[:,1].cumsum(out=a[:,1]) # accumulate values in the 2nd column
np.savetxt("output.txt", a) #note: you could specify fmt="%d" for integer array
with open('input.txt') as inf, open('output.txt','w') as outf:
datatype = int # or float
yy = 0
for line in inf:
x,y = line.split()
yy += datatype(y)
outf.write('{} {}'.format(x, yy))
data.txt:
1 10
2 20
3 30
4 40
コード:
with open('data.txt') as f1,open('output.txt','w') as f2:
lis=[map(int,line.split()) for line in f1]
for i,z in enumerate(lis):
f2.write("{0:d} {1:d}\n".format(z[0],sum(lis[j][1] for j in range(i+1))))
出力:
1 10
2 30
3 60
4 100