2014-09-10 72 views
-1

所以我在這個函數中有一個非常奇怪的錯誤,我認爲它必須與python引用有關,而不是賦值。如果任何人都可以看到是什麼導致mainList的值消失,我將非常感激。 - http://pastebin.com/6sZCwAk8刪除python引用,而不是複製

inputs: 
ships -> [0] 
hitListLength = 1 
output of first print statement [[0]] 
output of second print statement [[]] 

我的理論是,因爲我從countingList彈出它已經從mainList不知道如何避開這個刪除的價值?

def addPlacement(ships,hitListLength,start = None, mainList = None,countingList = None): 
    if start == None: 
     start=0 
    if mainList == None: 
     mainList = [] 
    if countingList == None: 
     countingList = [] 
    #pop ship from array for use on this recusion level 
    ship = ships.pop() 
    #loop through each hit 
    for x in range(start,hitListLength): 
     #add this rotation to the counting list 
     countingList.append(x) 
     #if we don't need to go any deeper add the counting array as an element of the main list 
     if len(ships) == 0: 
      mainList.append(countingList) 
      print "MainList: " + str(mainList) 
     else: 
      #otherwise recure deeper updating mainlist 
      mainList += addPlacement(ships,hitListLength,(start+1),mainList,countinglist) 
     #remove this loops countingList contribution so next loop can take its place 
     countingList.pop() 
    #return the mainlist 
    ships.append(ship) 
    print "MainList: " + str(mainList) 
    return mainList 
+0

你做一個深拷貝是這樣的複製'的newval = copy.deepcopy(OLDVAL)',但我不敢肯定這是這裏的問題。 – cdarke 2014-09-10 13:16:20

+0

將mainlist.append(countingList)更改爲mainlist.append(countingList [:])i,e slicing countingList應解決返回空mainList的問題 – Ram 2014-09-10 13:24:38

回答

0

你做

mainList.append(countingList) 

然後

countingList.pop() 

從countingList這讓你用[]僅刪除元素mainList

因爲追加追加到一個參考countingList,並且你從countingList中彈出唯一的元素,這個變化被反映出來在mainList以及

使用,如果你想countingList的副本存儲在mainList