我有一个函数legalMove(array, int)
,它意味着以数组的形式接受15问题的当前状态,然后根据数字命令进行移动。出于某种原因,这个函数正在改变我放入阵列点的数组。为什么这样,我该如何解决这个问题?我认为函数中的变量将保持该函数的局部变量,并且只有在我输入currentState = legalMove(currentState, command)
建议的数组输入:currentState = [8,13,1,4,2,14,0,5,3,12,10,7,11,6,9,15]
def legalMove(currentBoard, cmd):
#First, do the move
#0 = UP
#1 = RIGHT
#2 = LEFT
#3 = DOWN
blankPOS = currentBoard.index(0)
if cmd == 0: #go up
try:
exchangePOS = blankPOS - 4
numberE = currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
if cmd == 1: #go right
try:
exchangePOS = blankPOS + 1
numberE = currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
if cmd == 2: #go left
try:
exchangePOS = blankPOS - 1
numberE = currentBoard[exchangePOS]
print "blanksPOS",blankPOS
print "exchangePOS",exchangePOS
print "currentBoard[blankPOS]",currentBoard[blankPOS]
print "currentBoard[exchangePOS]",currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
if cmd == 3: #go down
try:
exchangePOS = blankPOS + 4
numberE = currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
return currentBoard
答案 0 :(得分:3)
我认为函数中的变量仍然是该函数的本地变量
一半是真的。在函数内部创建的变量在函数执行期间是可见的和活动的,不能从任何外部作用域访问,并且在函数执行完毕后不可用。
但是,在Python中,传递给函数的所有对象(尤其是列表)都是通过引用传递的,这意味着函数的更改会导致对象在其他位置发生更改。
示例:
>>> l = [1, 2, 3, 4]
>>> def func(some_list):
... some_list.append(5)
...
>>> func(l)
>>> l
[1, 2, 3, 4, 5]
为了避免这种情况,你需要向该函数传递一个该列表的副本(所以基本上创建一个新的对象,当在函数内部更改它时不会影响原始列表。)
您可以在将列表传递给函数时使用list()
文字实现此目的。
示例:
>>> l = [1, 2, 3, 4]
>>> def func(some_list):
... some_list.append(5)
...
>>> func(list(l))
>>> l
[1, 2, 3, 4]
>>>