gpt4 book ai didi

python - 如何在 Python 中将输入数据存储到多个矩阵中?

转载 作者:行者123 更新时间:2023-12-01 08:13:35 26 4
gpt4 key购买 nike

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

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 中读取外部文件,但不知道如何将此输入文件划分为多个矩阵,我该怎么做?

谢谢

最佳答案

你可以编写这样的代码:

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 ...

关于python - 如何在 Python 中将输入数据存储到多个矩阵中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com