修改文件纹理

2024-04-18 08:08:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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。等等

最终输出如下:

^{pr2}$

我试着用我写的代码:

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)

我还在每个ifelif语句中添加了更多的if和{}语句,以便检查第二列和第三列。但是,只更新了第四列。在

我做错什么了?在


Tags: ifvalueasline模式语句openfloat
2条回答
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) 

这在Python2.7中有效。我创造了我自己的abc.txt文档结果符合你想要的结果。在

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

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')

这将作为输出:

^{pr2}$

相关问题 更多 >