所以我在这个函数中有一个非常奇怪的错误我认为它必须与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
答案 0 :(得分:0)
mainList.append(countingList)
然后
countingList.pop()
只删除来自countingList的元素,它在mainList
中留下[]因为append会附加对countingList的引用,并且你从countingList中弹出唯一的元素,这个更改也会反映在mainList中
如果要在mainList
中存储countingList的副本,请使用copy