還是編程/腳本編程的新手,這個人一直在困擾着我。我有一個函數可以搜索名稱列表,將它與模板名稱列表進行比較,當它找到匹配項時,它會按正確的順序將它放入我的最終列表中。對於一些以後的函數能夠正常工作,我需要能夠將這些名稱的一部分作爲數組/列表附加。我遇到的問題是,每當我需要將列表添加到最終列表中時,只要我更改變量,最終列表就會隨之更新。我該如何解決?Python Lists追加可變變量
light = ['template of names in here in correct order']
listUser = ['names gathered from user input']
for userChan in listUser:
for channelName in light:
#check if channelName is a list or string
if isinstance(channelName, basestring):
#search for matches in userchan
print channelName, 'is a string'
if channelName in userChan.lower():
matchFound = True
listLight.append(userChan)
else:
print channelName, 'is a list'
for piece in channelName:
print 'searching %s in %s' %(piece, userChan.lower())
if piece in userChan.lower():
print "found %s in %s" %(piece, userChan.lower())
lightMultList.append(piece)
matchFound = True
if len(lightMultList) == 2:
listLight.append(lightMultList)
del lightMultList[:]
所以我的問題是與lightMultList。它總是被限制爲2個元素,但它會改變。希望這不是太可怕..
我可以' t安靜地告訴你想要做什麼,但是我的猜測是你在哪裏添加了一個你想要複製的列表而不是追加實際的列表。所以'listLight.append(lightMultList [:])' – Hoopdady
是的。就是這樣。超級簡單。謝謝 – CG7Son
@ CG7Son:在這種情況下有更好的解決方案。通過清除它('del lightMultList [:]')並重新填充它來停止重用'lightMultList'。 – abarnert