Python矩阵参数传递变异

2024-04-19 23:44:01 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮帮我吗! 我找不到错误的原因。如果我运行它一次,它工作正常,但是当我用相同的参数再次调用相同的方法时,它会保留列表的最后一个会话,而我从未保存它。我试着使用一个临时变量,但在我运行一次之后,它也被修改了( 此算法是:

def searchin(position, mattwo):
    listpos = -1
    indexone = -1
    # - - - - - -
    for i in mattwo:
        listpos += 1
        for o in i:
            if o == position:
                indexone = i.index(o)
                return listpos, indexone

def repos(reposition, listsone):
    cero, replacement = searchin('0',listsone),searchin(reposition,listsone)
    modded = listsone
    modded[replacement[0]][replacement[1]],modded[cero[0]][cero[1]] = '0', reposition

mat = [['5','4','1'],
       ['0','6','8'],
       ['7','3','2']]

repos('5',mat)
repos('7',mat)

方法serachin()返回我们要查找的元素在矩阵3x3中的位置。工作正常吗?没有错误

repos()方法就是问题所在。在我运行它之后,矩阵mat会随着上次运行的结果发生变化,但我从未保存它


Tags: 方法def错误positionreposmatreplacementindexone
2条回答

这就是你想做的吗

from copy import deepcopy

def findpos(element, matrix):
    ii = -1
    jj = -1
    for i in matrix:
        ii += 1
        for o in i:
            if o == element:
                jj = i.index(o)
                return ii, jj

def switchmatrixelements(el1,el2, mat):
    pos1 = findpos(el1,mat)
    pos2 =  findpos(el2,mat)
    modded =  deepcopy(mat)
    modded[pos2[0]][pos2[1]] = el1
    modded[pos1[0]][pos1[1]] = el2
    return modded

mat = [['5','4','1'],
       ['0','6','8'],
       ['7','3','2']]

print mat
print switchmatrixelements('0','5',mat)
print switchmatrixelements('0','7',mat) 

输出:

   [['5', '4', '1'], ['0', '6', '8'], ['7', '3', '2']]
   [['0', '4', '1'], ['5', '6', '8'], ['7', '3', '2']]
   [['5', '4', '1'], ['7', '6', '8'], ['0', '3', '2']]

您需要在repos中执行listone的深度复制

from copy import deepcopy添加到文件顶部,然后将modded = listsone更改为modded = deepcopy(listsone)。在repos函数的末尾,返回modded。调用repos时,将返回值赋给变量。例如,将repos('5',mat)更改为some_variable = repos('5',mat)

相关问题 更多 >