【问题标题】:How do I Store input data into multiple matrices in Python?如何在 Python 中将输入数据存储到多个矩阵中?
【发布时间】:2019-03-10 05:02:46
【问题描述】:

我有一个包含多个矩阵的文本文件,如下所示:

4 5 1
4 1 5
1 2 3
[space]
4 8 9
7 5 6
7 4 5
[space]
2 1 3
5 8 9
4 5 6

我想在 python 中读取这个输入文件并将其存储在多个矩阵中,例如:

matrixA = [...] # first matrix
matrixB = [...] # second matrix

等等。我知道如何在 python 中读取外部文件,但不知道如何将此输入文件划分为多个矩阵,我该怎么做?

谢谢

【问题讨论】:

  • 说完所有的事情后,您将拥有多少个矩阵?可变金额? 10? 1,000,000?一旦它们以您想要的方式存储,您打算如何处理它们?您会反复使用此代码还是一次性使用此代码?

标签: python matrix multidimensional-array input storing-data


【解决方案1】:

你可以这样写代码:

all_matrices = []  # hold matrixA, matrixB, ...
matrix = []  # hold current matrix
with open('file.txt', 'r') as f:
    values = line.split()
    if values:  # if line contains numbers
        matrix.append(values)
    else:  # if line contains nothing then add matrix to all_matrices
        all_matrices.append(matrix)
        matrix = []
# do what every you want with all_matrices ...

【讨论】:

  • 您忘记关闭文件。 with open(...) as f: 是一个非常有用的成语。还有一个小提示:strip 在spilit 之前不需要。
【解决方案2】:

我确信算法可以在某处进行优化,但我找到的答案很简单:

file = open('matrix_list.txt').read() #Open the File
matrix_list = file.split("\n\n") #Split the file in a list of Matrices
for i, m in enumerate(matrix_list): 
    matrix_list[i]=m.split("\n") #Split the row of each matrix
    for j, r in enumerate(matrix_list[i]): 
        matrix_list[i][j] = r.split() #Split the value of each row

这将导致以下格式:

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

如何使用列表的示例:

print(matrix_list) #prints all matrices
print(matrix_list[0]) #prints the first matrix
print(matrix_list[0][1]) #prints the second row of the first matrix
print(matrix_list[0][1][2]) #prints the value from the second row and third column of the first matrix

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多