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

标签 python arrays numpy

我有一个这样的列表:

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.

关于python - 从python中的列表创建一个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45775196/

相关文章:

java - 我需要从控制台输入的字符串中删除空格

python - 使用 Numpy.loadtxt() 进行并行处理

python - “numpy”没有属性 'core'

Ruby每道逻辑题

python - 输入层的 TensorFlow Keras 维度误差

java - 在java中使用hashmap创建嵌套映射来完成嵌套数组但不起作用

python - 有没有办法将列表中的元素插入到第二个列表中的每个第 kn 个位置?

numpy - 使用元组列表索引 numpy 数组

python - 如何去除附着在另一个大轮廓上的小轮廓

python - 比较两个日期时出错