【问题标题】:How to read two matrices from a single input file in Python如何从 Python 中的单个输入文件中读取两个矩阵
【发布时间】:2018-05-27 17:42:27
【问题描述】:

我已将两个矩阵 A 和 B 保存在一个 .txt 文件中,如下所示。

矩阵 A:

2,4,5

4,7,3


矩阵 B:

1,2

5,9

1,6

在 Python 中,如何从这个输入文件中分别读取两个矩阵 A 和 B。

【问题讨论】:

    标签: python io


    【解决方案1】:

    假设您的输入文件看起来像这样(矩阵由空行分隔):

    2,4,5
    4,7,3
    
    1,2
    5,9
    1,6
    

    这个python代码(用于python3):

    input_file = open('input.txt', 'r')
    a = []
    b = []
    current = a # Current will point to the current matrix
    
    for line in input_file.readlines():
        if ',' not in line: # This is our separator - a line with no ',', switch a matrix
            current = b
        else:
            current.append([]) # Add a row to our current matrix
            for x in line.split(','): # Values are separated by ','
                current[len(current) - 1].append(int(x)) # Add int(x) to the last line
    
    print(a, b)
    input_file.close()
    

    输出以下内容:

    [[2, 4, 5], [4, 7, 3]] [[1, 2], [5, 9], [1, 6]]
    

    【讨论】:

    • 它显示错误信息:“ValueError: invalid literal for int() with base 10: '\n'”
    • 您的矩阵似乎由'\n'分隔,而不是'\n' - 这不是空行,而是带空格的行。我编辑了答案,使其使用不带“,”的行来分隔矩阵。现在应该可以了,请再试一次。
    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多