通过Numpy中的矩阵索引列表访问矩阵

时间:2014-06-03 09:43:25

标签: python numpy matrix

我有一个矩阵索引列表,想要通过这些索引访问矩阵。

示例:

indices = [(2, 0), (2, 1), (2, 2)]
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mat[indices] = 0

这会导致[[1, 2, 3], [4, 5, 6], [0, 0, 0]],但不幸的是我总是得到“list indices must be integers, not list”。

修改

正如user2357112在他的评论中所说,我现在尝试了以下内容:

mat = numpy.array(mat)
indices = numpy.array(indices)
mat[indices] = 0

但不幸的是,现在整个矩阵都填充了0。

2 个答案:

答案 0 :(得分:2)

indices是元组的常规列表,无法用于获取常规 mat的元素。您可以做的是遍历您的列表以获取您的索引:

for x, y in indices:
    mat[x][y] = 0

如果要使用numpy方法,则需要创建一个numpy数组。实际上,np.array结构允许使用元组来访问元素:

mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
for item in indices:
    mat[item] = 0

答案 1 :(得分:0)

您可以使用input[type="radio"]:checked+label{ color: #CE5A0B; font-weight: bold; } 来访问numpy数组 索引清单:

zip(*indices)