Skip to main content
 首页 » 编程设计

python之从python中的列表创建一个矩阵

2025年05月04日14小虾米

我有一个这样的列表:

A=[["a_00",0,0],["a_01",0,1],["a_02",0,2],["a_03",0,3], ["a_10",1,0],["a_11",1,1],["a_12",1,2],["a_13",1,3], ["a_20",2,0],["a_21",2,1],["a_22",2,2],["a_23",2,3], ["a_30",3,0],["a_31",3,1],["a_32",3,2],["a_33",3,3]] 

产生:

In [187]: A 
Out[187]: 
[['a_00', 0, 0], 
 ['a_01', 0, 1], 
 ['a_02', 0, 2], 
 ['a_03', 0, 3], 
 ['a_10', 1, 0], 
 ['a_11', 1, 1], 
 ['a_12', 1, 2], 
 ['a_13', 1, 3], 
 ['a_20', 2, 0], 
 ['a_21', 2, 1], 
 ['a_22', 2, 2], 
 ['a_23', 2, 3], 
 ['a_30', 3, 0], 
 ['a_31', 3, 1], 
 ['a_32', 3, 2], 
 ['a_33', 3, 3]] 

我想变成这样的矩阵:

B=[["a_00","a_01","a_02","a_03"], ["a_10","a_11","a_12","a_13"], ["a_20","a_21","a_22","a_23"], ["a_30","a_31","a_32","a_33"]]  

产量:

In [188]: B 
Out[188]: 
[['a_00', 'a_01', 'a_02', 'a_03'], 
 ['a_10', 'a_11', 'a_12', 'a_13'], 
 ['a_20', 'a_21', 'a_22', 'a_23'], 
 ['a_30', 'a_31', 'a_32', 'a_33']] 

我为了我的目的写了这段代码:

import numpy 
B=numpy.zeros(7,7) 
for item in A: 
    B[item[1]][item[2]]=item[0] 

但我看到这个错误:

IndexError: list index out of range

我该怎么办?

请您参考如下方法:

你的代码看起来不错,除了 1 行 B=numpy.zeros(7,7) 它应该是 B=numpy.zeros((7,7))

根据 documentation

A=[[1,0,0],[2,0,1],[3,0,2], 
[4,1,0],[5,1,1],[6,1,2], 
[7,2,0],[8,2,1],[9,2,2]] 
 
import numpy as np 
 
B = np.zeros((3,3)) 
for item in A: 
    B[item[1]][item[2]]=item[0] 
 
B 
 
array([[ 1.,  2.,  3.], 
       [ 4.,  5.,  6.], 
       [ 7.,  8.,  9.]]) 

您也可以使用 reshape 以简单的方式完成

np.array(A)[:,0].reshape(7,7) 

工作原理:

np.array(A) 
array([[a_00, 0, 0], 
       [a_01, 0, 1], 
       [a_02, 0, 2], 
       ... 
 
np.array(A)[:,0] 
array([a_00, a_01, a_02,...]) 
 
np.array(A)[:,0].reshape(3,3) # reshape it in the shape that we care for.