所以我在这个函数中有一个非常奇怪的错误,我认为它一定与python引用有关,而不是与值分配有关。如果有人能看到是什么导致mainList的价值消失,我将不胜感激。-http://pastebin.com/6sZCwAk8
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
您执行
mainList.append(countingList)
然后
countingList.pop()
它只从countingList中删除元素,在mainList 中留下[]
由于append附加了对countingList的引用,并且您从countingList中弹出了唯一的元素,因此此更改也反映在mainList和中
如果您想在mainList 中存储countingList的副本,请使用copy