繁体   English   中英

将特定列中的数字乘以3

[英]multiply the numbers in a specific column by factor of 3

我想将特定列(以下输入文件xyz.txt中的z列)中的所有数字乘以3并将其输出到文本文件中。 当我运行./script.py xyz.txt > output.txt此错误:

追溯(最近一次呼叫最近):sys.exit(main(sys.argv))中的文件“ ./script.py”,第23行,主要结果中的文件“ ./script.py”,行18,append( z.split('')[2] * 3)IndexError:列表索引超出范围

您知道如何解决此错误吗?

script.py:

#!/usr/bin/env python3

def main(argv):

    inputfile = open(argv[1])

    line = inputfile.readline()

    while line:
        print(line, end="")
        if line.startswith('[ xyz ]'):
            break
        line = inputfile.readline()

    result=[]
    for z in line:
        result.append(z.split(' ')[2]*3)
        print(z.rstrip(), '; modified')

if __name__ == "__main__":
    import sys
    sys.exit(main(sys.argv))

输入文件xyz.txt:

[ xyz ]
;     x     y      z  
     1.5   3.5     6.3
     2.4   4.2     2.4
     3.2   8.9     8.9
     4.3   2.1     9.2
     5.4   6.3     3.5 

请求的输出文件output.txt:

[ xyz ]
;     x     y      z  
     1.5   3.5    18.9 ; modified
     2.4   4.2     7.2 ; modified
     3.2   8.9    26.7 ; modified
     4.3   2.1    27.6 ; modified
     5.4   6.3    10.5 ; modified
import sys


def main(argv):

    inputfile = open(argv[1])

    line = inputfile.readline()

    result = []

    while line:

        # print(line, end="")
        # print(line)
        # print(len(line))
        # print(line.strip())
        # print(len(line.strip()))
        # print(line.strip().endswith("z"))
        # print("*" + line + "*")

        if line.strip().endswith("z"):
            result.append(line)
            line = inputfile.readline()
            continue


        # print()
        # print(line)
        # print("Z line")
        # print(line)
        # print(type(line))

        prev = line[:-5]
        z = line[-4:-1]

        # print(z)

        try:
            z = float(z)
        except ValueError:
            pass

        # print(type(z))
        # print()

        z = z * 3

        # print(z)

        z = str(z) + " ; modified"

        # print(z)

        output_line = prev + z

        # print(output_line)

        result.append(output_line)
        line = inputfile.readline()

    print(result)



if __name__ == "__main__":
    sys.exit(main(sys.argv))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM