防止在 if 语句 python 中进行更改

Preventing a change back once made in if statement python

我正在尝试更改 3 x 3 矩阵中的所有列值以遵循以下规则:

这是我目前所能做到的

def solve(x):
    if x[x == 1].all() == True:
        x[x == 1] = 5
    if x[x == 5].all() == True:
        x[x == 5] = 1
    if x[x == 2].all() == True:
        x[x == 2] = 6
    if x[x == 6].all() == True:
        x[x == 6] = 2
    if x[x == 3].all() == True:
        x[x == 3] = 4
    if x[x == 4].all() == True:
        x[x == 4] = 3
    if x[x == 8].all() == True:
        x[x == 8] = 9
    if x[x == 9].all() == True:
        x[x == 9] = 8
    return x

我遇到的问题是说 1 变为 5,如何防止它再次回到 1?我试过合并 elif 但它并不总能产生正确的结果。例如说我 运行 这个数组到我的函数中:

 array([[3, 1, 2],
        [3, 1, 2],
        [3, 1, 2]])

我希望看到

array([[4, 5, 6], 
       [4, 5, 6], 
       [4, 5, 6]])

但我最终还是得到了输入

array([[3, 1, 2],
       [3, 1, 2],
       [3, 1, 2]])

如何在 if 语句中解决这个问题?

这里有一些选项,都用d = {0: 0, 1: 5, 2: 6, ...}映射old_val: new_val:

  1. 使用np.vectorize映射old_val: new_val:
solved = np.vectorize(lambda i: d[i] if i in d else i)(arry)
  1. 创建一个副本并将其更改为替换版本,使用原始数组检查:
def solve(x):
    res = x
    for ov in d:
        res[x == ov] = d[ov]
    return res