首页 > 解决方案 > Numpy 不交换元素

问题描述

我正在尝试交换 NumPy 的二维数组中的两个索引。不幸的是,只有一个元素被交换。这是代码:

n = len(A)
perMatrix = np.zeros((n,n))
np.fill_diagonal(perMatrix, 1)
perMatrix = A

# swapping the row
print(perMatrix)
temp = perMatrix[switchIndex1]
print(temp)
# perMatrix[switchIndex1][0] = 14
perMatrix[switchIndex1], perMatrix[switchIndex2] = perMatrix[switchIndex2], perMatrix[switchIndex1]
print(perMatrix)

这是代码输出的内容:

输出图像

标签: pythonarraysnumpy

解决方案


您可以添加(在创建 perMatrix 后的行上):

sigma = [switchIndex1, switchIndex2]
tau   = [switchIndex2, switchIndex1]
perMatrix[sigma,:] = perMatrix[tau,:]

推荐阅读