我有一个包含此格式矩阵的文本文件:http://textuploader.com/d0qmb 每个整数必须在矩阵中占据自己的位置。我编写了这段代码,允许我为矩阵中的每一行打印数组,但我不知道如何附加每个数组来创建矩阵。
import numpy as np
# rows, cols not used in code. Just for info
rows = 9
cols = 93
with open('bob.txt') as f:
while True:
i=0
str = f.readline()
str = str.strip()
d = list(str)
d = map(int, d)
if not str: break
print(d)
i += 1
答案 0 :(得分:1)
import numpy as np
array = []
with open('bob.txt', 'r') as f:
for line in f:
array.append(array.append([int(i) for i in list(line) if i.isdigit()]))
numpy_array = np.array(array)
python中的 [int(i) for i in list(line) if i.isdigit()]
为a list comprehension。
它大致相同:
for character in line:
if character is:
cast this character to an int and append it to the list