所以我有一個列表,並且在for循環中,我追加了一組構造爲列表的座標,但是一旦返回,它只包含最後生成的座標,它會替換所有其他項主列表。 仔細檢查後,我每次追加東西時,都會用當前座標替換主列表中的所有項目。 爲什麼? 而源代碼可能不會幫助,它的確如此。 謝謝! 這裏的一些代碼:Python列表分配不起作用
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
因爲你可能做過'x = some_list'創建一個參考或類似的東西 – 2015-04-03 01:39:27
請給出一些代碼。 – thinkerou 2015-04-03 01:39:51
可能因爲您正在分配而不是追加。請顯示你的代碼。 – Barmar 2015-04-03 01:39:58