因此,我有一个列表,在for循环中,我追加了一组构造为列表的坐标,但是一旦返回,它仅包含最后产生的坐标,并替换了主列表中的所有其他项。仔细检查后,每次我添加一些内容时,它都会用当前坐标替换主列表中的所有项目。为什么?源代码可能无济于事,这正是它的发音。谢谢!这里有一些代码:
def createLab(size=16):
maze = createMaze()
answerPath=[]
visual=['o']*(size**2)
pos=[(size**2)/2,(size**2)/2]
lat='north'
for move in maze:
#print move, lat, pos
#print answerPath
answerPath.append(pos)
#answerPath='[%s, %s]' % (answerPath,pos)
if move=='straight':
if lat=='north': pos[1]=pos[1]+size
elif lat=='south': pos[1]=pos[1]-size
elif lat=='east': pos[0]=pos[0]+1
elif lat=='west': pos[0]=pos[0]-1
elif move=='left':
if lat=='north': pos[1]=pos[1]-1; lat='west'
elif lat=='south': pos[1]=pos[1]+1; lat='east'
elif lat=='east': pos[0]=pos[0]+size; lat='north'
elif lat=='west': pos[0]=pos[0]-size; lat='south'
elif move=='right':
if lat=='north': pos[1]=pos[1]+1; lat='east'
elif lat=='south': pos[1]=pos[1]-1; lat='west'
elif lat=='east': pos[0]=pos[0]-size; lat='south'
elif lat=='west': pos[0]=pos[0]+size; lat='north'
#print pos
#print; print
return answerPath, maze, pos
你正在创建一个pos
循环之前列表,并要追加完全相同的pos
到answerPath
一遍又一遍,并修改同一个pos
一遍又一遍。
作为解决方案,请pos
在每次迭代开始时使用切片符号创建一个浅表副本,以创建一个新副本:
def createLab(size=16):
maze = createMaze()
answerPath=[]
visual=['o']*(size**2)
pos=[(size**2)/2,(size**2)/2]
lat='north'
for move in maze:
pos = pos[:] #pos is now a new list with the same values as the previous pos
#Alternatively: pos = list(pos)
answerPath.append(pos)
if move=='straight':
if lat=='north': pos[1]=pos[1]+size
elif lat=='south': pos[1]=pos[1]-size
elif lat=='east': pos[0]=pos[0]+1
elif lat=='west': pos[0]=pos[0]-1
elif move=='left':
if lat=='north': pos[1]=pos[1]-1; lat='west'
elif lat=='south': pos[1]=pos[1]+1; lat='east'
elif lat=='east': pos[0]=pos[0]+size; lat='north'
elif lat=='west': pos[0]=pos[0]-size; lat='south'
elif move=='right':
if lat=='north': pos[1]=pos[1]+1; lat='east'
elif lat=='south': pos[1]=pos[1]-1; lat='west'
elif lat=='east': pos[0]=pos[0]-size; lat='south'
elif lat=='west': pos[0]=pos[0]+size; lat='north'
return answerPath, maze, pos
有关pos
您的示例和我的实际情况的指针,我建议阅读Wesley Chun关于Python的Memory Model的出色幻灯片。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句