-3

我有一个 txt 文件,每行包含由空格分隔的 2 个值:

x1 y1
x2 y2
x3 y3
...
xn yn

我想获取另一个文件,其中包含:

x1 y1
x2 y1+y2
x3 y1+y2+y3
...
xn y1+y2+y3+...+yn

在 python 中最快(我的意思是最简单)的方法是什么?

4

4 回答 4

3

这会让你开始

给定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

我怀疑上面的代码,尤其是第二个代码,可能会被进一步简化/优化,但应该足以让你开始。

您仍然需要调整从字符串到适当类型(floatint)的转换,并创建输出文件并以您喜欢的格式写入它。这些是您最好决定的细节。

于 2012-07-08T16:55:28.113 回答
2

最简单的代码方式是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
于 2012-07-08T17:49:29.987 回答
1
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))
于 2012-07-08T17:15:31.653 回答
0

数据.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
于 2012-07-08T17:51:48.630 回答