如何在Python中交换三维数组中的值



我有一个矩阵(3x5(,其中一个数字是在这个矩阵中随机选择的。我想把选中的号码和右边的号码交换。我可以找到随机选择的数字的索引,但不知道如何将其替换为向下然后向右的数字。例如,给定矩阵:

[[169 107 229 317 236]
[202 124 114 280 106]
[306 135 396 218 373]]

并且所选数字是280(位于位置[1,3](,需要与[2,4]上的373交换。我在如何使用索引方面遇到了问题。我可以硬编码,但当随机选择要交换的数字时,它会变得有点复杂。

如果选择的数字是[0,0],那么硬编码看起来像:

selected_task = tard_generator1[0,0]
right_swap = tard_generator1[1,1]
tard_generator1[1,1] = selected_task
tard_generator1[0,0] = right_swap

欢迎提出任何建议!

像这样的东西怎么样

chosen = (1, 2)
right_down = chosen[0] + 1, chosen[1] + 1
matrix[chosen], matrix[right_down] = matrix[right_down], matrix[chosen]

将输出:

>>> a
array([[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> index = (1, 2)
>>> right_down = index[0] + 1, index[1] + 1
>>> a[index], a[right_down] = a[right_down], a[index]
>>> a
array([[ 0,  1,  2,  3,  4],
[ 5,  6, 13,  8,  9],
[10, 11, 12,  7, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])

应该有边界检查,但省略了

试试这个:

import numpy as np
def swap_rdi(mat, index):
row, col = index
rows, cols = mat.shape
assert(row + 1 != rows and col + 1 != cols)
mat[row, col], mat[row+1, col+1] = mat[row+1, col+1], mat[row, col]
return

示例:

mat = np.matrix([[1,2,3], [4,5,6]])
print('Before:n{}'.format(mat))
print('After:n{}'.format(swap_rdi(mat, (0,1))))

输出:

Before:
[[1 2 3]
[4 5 6]]
After:
[[1 6 3]
[4 5 2]]    

最新更新