Python矩阵参数传递变异

时间:2016-03-09 23:33:33

标签: python matrix

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

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()方法就是问题所在。在我运行它之后,矩阵垫会随着最后一次运行的结果而变异但是我永远不会保存它。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

这是你想要做的吗?

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