我很难理解为什么expqueue会不断更改为状态的多次迭代, 从[:]到深度复制,我都试过了。有人能解释什么不对吗? 代码是一个8字谜游戏,如果我能得到一个运行列表去所有不同的 我相信我能自己完成,是的,这是家庭作业。你知道吗
import copy
init = [[2,0,3], [1,5,6],[4,7,8]]
goal = [[1,2,3], [4,5,6],[7,8,0]]
expqueue = []
tempqueue = []
depth = 0
def myappend(lst1, lst2):
new = list(lst1)
new2 = list(lst2)
new.append(new2)
global expqueue
expqueue = new
def makeState(state):
for x in range(0,3):
for i in range(0,3):
print state[x][i],
print "\n"
def locate(state):
for x in range(0,3):
for y in range(0,3):
if state[x][y] == 0:
return [x, y]
def moveU(state):
location = locate(state)
x = location[0]
y = location[1]
s = x-1
if x>0:
swap = state[x][y]
state[x][y] = state[s][y]
state[s][y] = swap
myappend(expqueue, state)
def moveL(state):
location = locate(state)
x = location[0]
y = location[1]
s = y-1
if y>0:
swap = state[x][y]
state[x][y] = state[x][s]
state[x][s] = swap
myappend(expqueue, state)
def moveR(state):
location = locate(state)
x = location[0]
y = location[1]
s = y+1
if y<2:
swap = state[x][y]
state[x][y] = state[x][s]
state[x][s] = swap
myappend(expqueue, state)
def moveD(state):
location = locate(state)
x = location[0]
y = location[1]
s = x+1
if x<2:
swap = state[x][y]
state[x][y] = state[s][y]
state[s][y] = swap
myappend(expqueue, state)
def expand(lst):
tempqueue = lst[:]
while tempqueue != []:
state = tempqueue[0]
current = state[:]
moveU(current)
moveL(current)
moveR(current)
moveD(current)
del tempqueue[0]
return expqueue
def solve(queue, initial, solution, level):
length = len(queue)
for x in range(length):
if queue[x] == solution:
return "This works!"
return solve(expand(queue), initial, solution, level+1)
print solve([init], init, goal, 0)
从那以后,我在最初的切片上添加了deepcopy,并且我注意到ID在复制之后会恢复原样。有人知道为什么吗?你知道吗
显然我没有足够的街头信誉来发布截图,所以这里有一个链接: Matching id's after copy
您正在更改嵌套的列表,但只复制了外部列表;
list(original)
或original[:]
调用只创建一个浅层副本;新列表“继承”对内容的引用,如果这些内容是可变的,那么您将在这两个位置看到对这些内容的更改。你知道吗创建嵌套列表的副本:
以及
这将创建每个嵌套列表的浅表副本。你知道吗
或者使用^{} function 递归地复制对象。你知道吗
tempqueue = lst[:]
生成浅拷贝,而不是深拷贝。这意味着您将获得一个新的容器列表,但引用的内容完全相同。因为内容本身就是列表,所以您将获得对可变对象的引用。如果在lst
或tempqueue
中对这些列表进行变异,那么另一个列表也会受到影响。你知道吗如果您想要列表的深度副本,可以使用
或者
或者
或者,对于更深层的嵌套结构,可以使用
example here显示了使用浅拷贝和深拷贝的区别。你知道吗
相关问题 更多 >
编程相关推荐