如何在Python中交换3d数组中的值?

2024-05-12 20:43:53 发布

您现在位置: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

欢迎提出任何建议


Tags: right编码task矩阵数字建议号码selected
2条回答

像这样的怎么样

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]]    

相关问题 更多 >