Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中交换三维数组中的值?_Python_Multidimensional Array_Matrix Indexing - Fatal编程技术网

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

如何在Python中交换三维数组中的值?,python,multidimensional-array,matrix-indexing,Python,Multidimensional Array,Matrix Indexing,我有一个矩阵(3x5),其中一个数字是在这个矩阵中随机选择的。我想把选定的号码换成右下的号码。我能够找到随机选择的数字的索引,但不确定如何用向下然后向右的数字替换它。例如,给定矩阵: [[169 107 229 317 236] [202 124 114 280 106] [306 135 396 218 373]] 选择的数字是280(位于位置[1,3]),需要与[2,4]上的373交换。我对如何使用索引有疑问。我可以硬编码,但当随机选择要交换的数字时,它会变得有点复杂 如果选定的数字为

我有一个矩阵(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]]    

这回答了你的问题吗?