还是编程/脚本编程的新手,这个人一直在困扰着我。我有一个函数可以搜索名称列表,将它与模板名称列表进行比较,当它找到匹配项时,它会按正确的顺序将它放入我的最终列表中。对于一些以后的函数能够正常工作,我需要能够将这些名称的一部分作为数组/列表附加。我遇到的问题是,每当我需要将列表添加到最终列表中时,只要我更改变量,最终列表就会随之更新。我该如何解决?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