【问题标题】:multiply the numbers in a specific column by factor of 3将特定列中的数字乘以 3
【发布时间】:2018-06-19 15:05:20
【问题描述】:

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

Traceback(最近一次调用最后一次):文件“./script.py”,第 23 行,在 sys.exit(main(sys.argv)) 文件“./script.py”,第 18 行,在 main result.append(z.split(' ')[2]*3) IndexError: list index out of range

你知道我该如何解决这个错误吗?

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

【问题讨论】:

  • 您似乎正在像换行符一样拆分绞线。此外,您应该使用csv 模块来读取更适合此类任务的文件。或者作为更好的方法,您可以使用 numpypandas 模块。
  • 你可以做if (len(z.split(' ')>2): result.append(z.split(' ')[2]*3)
  • @erhan:您必须将文件转储为 txt。您还需要管理列表中 z 值的索引。

标签: python python-3.x numpy


【解决方案1】:
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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2023-02-20
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多