1

我有一个这样的文本文件:

0  1  0  10.2  5.82  4.82
1 -1  0  8.21  5.74  3.62
0  1  1  5.33  8.66  5.47

这个文本文件有几百行具有这种模式。

在第一行中,如果第一列为 0,则第四列相同。第二列是 1,第五列是 +10,所以值为 15.82。

在第二行中,如果第一列为 1,则第四列为 +10,因此值为 18.21。第二列是-1,第五列是-10,所以值为-4.26。等等

最终输出是这样的:

10.20  15.82  4.82
18.21  -4.26  3.62
 5.33  18.66  15.47

我试过使用我写的这段代码:

with open('abc') as f, open('out.txt', 'w') as f1:
    for line in f:
        reff = line.split()

        if reff[0] == '0':
            value = float(reff[3])
            a = str(value)
            line = "".join(a) + " " + "".join(reff[4]) + " " + "".join(reff[5]) + '\n'

        elif reff[0] == '1':
            value = float(reff[3]) + 10
            a = str(value)
            line = "".join(a) + " " + "".join(reff[4]) + " " + "".join(reff[5]) + '\n'

        elif reff[0] == '-1':
            value = float(reff[3]) - 10
            a = str(value)
            line = "".join(a) + " " + "".join(reff[4]) + " " + "".join(reff[5]) + '\n'

        f1.write(line)

我还在每个and语句中添加了更多ifand语句,以便检查第二列和第三列。但是,仅更新了第四列。elififelif

我究竟做错了什么?

4

2 回答 2

5

这实际上可以非常简单地完成:

with open('abc') as f, open('out.txt', 'w') as f1:
    for line in f:
        line = line.split()
        for i in range(0,3):
            line[i+3] = float(line[i+3])+(int(line[i])*10)
        f1.write(' '.join([str(value) for value in line[3:]]) + '\n')

这将为您提供输出:

10.2 15.82 4.82
18.21 -4.26 3.62
5.33 18.66 15.47
于 2013-08-07T18:55:01.527 回答
1
with open('abc.txt') as f, open('out.txt', 'w') as f1:

    modifyDict = { 0:0,
                   1:10,
                  -1:-10}


    for line in f:
        reffLine = line.split()

        reffInfo = []
        for i, reff in enumerate(reffLine[:3]):
            criteria = int(reff)
            value = float(reffLine[i+3]) + modifyDict[criteria]
            a = str(value)
            reffInfo.append(a)

        templine = " ".join(reffInfo)
        line = templine + '\n'

        f1.write(line) 

这适用于 python 2.7。我创建了自己的 abc.txt,结果与您想要的输出相匹配。

于 2013-08-07T19:31:15.790 回答