我有一个包含这些值的2D列表:
text = [[4, 3, 8, 9, 5, 1, 2, 7, 6], [8, 3, 4, 1, 5, 9, 6, 7, 2],
[6, 1, 8, 7, 5, 3, 2, 9, 4], [6, 9, 8, 7, 5, 3, 2, 1, 4],
[6, 1, 8, 7, 5, 3, 2, 1, 4], [6, 1, 3, 2, 9, 4, 8, 7, 5]]
Run Code Online (Sandbox Code Playgroud)
例如,text [i]应该这样打印:
4 3 8
9 5 1
2 7 6
Run Code Online (Sandbox Code Playgroud)
但我的矩阵打印此:
r = 6
m = []
for i in range(r):
m.append([int(x) for x in text[i]])
for i in m:
print (i)
>>
4 3 8 9 5 1 2 7 6
8 3 4 1 5 9 6 7 2
6 1 8 7 5 3 2 9 4
6 9 8 7 5 3 2 1 4
6 1 8 7 5 3 2 1 4
6 1 3 2 9 4 8 7 5
Run Code Online (Sandbox Code Playgroud)
您可以使用numpy。首先,将您的列表转换为numpy数组。然后,取一个元素并将其重塑为3x3矩阵。
import numpy as np
text = [[4, 3, 8, 9, 5, 1, 2, 7, 6], [8, 3, 4, 1, 5, 9, 6, 7, 2],
[6, 1, 8, 7, 5, 3, 2, 9, 4], [6, 9, 8, 7, 5, 3, 2, 1, 4],
[6, 1, 8, 7, 5, 3, 2, 1, 4], [6, 1, 3, 2, 9, 4, 8, 7, 5]]
text = np.array(text)
print text[0].reshape((3, 3))
print text[1].reshape((3, 3))
Run Code Online (Sandbox Code Playgroud)
输出:
[[4 3 8]
[9 5 1]
[2 7 6]]
[[8 3 4]
[1 5 9]
[6 7 2]]
Run Code Online (Sandbox Code Playgroud)
使用numpy,您实际上正在处理矩阵