2015-04-03 79 views
-2

所以我有一個列表,並且在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 
+0

因爲你可能做過'x = some_list'創建一個參考或類似的東西 – 2015-04-03 01:39:27

+2

請給出一些代碼。 – thinkerou 2015-04-03 01:39:51

+2

可能因爲您正在分配而不是追加。請顯示你的代碼。 – Barmar 2015-04-03 01:39:58

回答

1

你正在創建循環之前一個pos列表,你一遍又一遍追加完全相同的posanswerPath,並一遍又一遍地修改同一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's excellent slides on Python's Memory Model

+0

工作!如何簡單的工作?我之前只是參考了嗎? – 2015-04-03 07:02:28

+0

是的,當您將某些內容附加到列表中時,您實際上是在存儲對正在追加的對象的引用。對於循環的每一次迭代,您都在存儲對同一對象的新引用,然後對該對象進行變異 - 因此列表中的每個引用都會反映相同的變化。 – zehnpaard 2015-04-03 08:16:58

0

沒有代碼,我們不能真正幫助你太多。從你的描述中,聽起來好像你沒有將新的座標追加到列表中,而是寫在同一個列表上。

請向我們提供相關代碼。

在代碼中嘗試類似.append的內容。例如。

名單= [一,二,三]

list.append(四)個

打印(列表)

打印現在應該爲您提供以下結果。

一,二,三,四

我希望這對你有所幫助。

+0

好吧,我添加了一些代碼 – 2015-04-03 03:25:00