String 从列表中删除某些项目
我正在研究如何从列表中删除特定项String 从列表中删除某些项目,string,list,python-2.7,String,List,Python 2.7,我正在研究如何从列表中删除特定项 "peppers", "cheese", "mushrooms", "bananas", "peppers" 我可以找到项目“peppers”,并将其更改为“gone!”,但我确实想使用 del blist[idx] 但这会导致一个错误,我不知道为什么 myList = ["peppers", "cheese", "mushrooms", "bananas", "peppers"] def findInList (needle, haystack):
"peppers", "cheese", "mushrooms", "bananas", "peppers"
我可以找到项目“peppers”,并将其更改为“gone!”,但我确实想使用
del blist[idx]
但这会导致一个错误,我不知道为什么
myList = ["peppers", "cheese", "mushrooms", "bananas", "peppers"]
def findInList (needle, haystack):
needle = needle.lower()
findy = []
# loops over list elements
for i in range(0, len(haystack)):
temp = haystack[i].lower()
idx = temp.find(needle)
if (idx != -1): findy.append(i)
return findy
def deleteItemInList(alist, blist):
for i in range(0, len(alist)):
idx = alist[i]
blist[idx] = "Gone!"
# del blist[idx]
# find items in list
mySearch = findInList("Peppers", myList)
# remove item from list
deleteItemInList(mySearch, myList)
print myList
回溯:如下所示
Traceback (most recent call last):
File "delete_in_list.py", line 23, in <module>
deleteItemInList(mySearch, myList)
File "delete_in_list.py", line 16, in deleteItemInList
blist[idx] = "Gone!"
IndexError: list assignment index out of range
回溯(最近一次呼叫最后一次):
文件“delete_in_list.py”,第23行,在
deleteItemInList(mySearch,myList)
文件“delete_in_list.py”,deleteItemInList第16行
blist[idx]=“消失!”
索引器:列表分配索引超出范围
有人能看一下上面的代码并指出我的错误所在吗。要查找元素,请使用此函数。或者,也可以像往常一样定义它:
>>> find = lambda _list, query: [item.lower() for item in _list].index(query.lower())
>>> l = ['red', 'pepper']
>>> q = 'Pepper'
>>> find(l, q)
1
要按索引删除,只需使用del
:
>>> del l[find(l, q)]
>>> l
['red']
您可以使用列表来理解这一点
def removeWord(needle, haystack):
return [word for word in haystack if word.lower() != needle.lower()]
我终于明白了!当我在列表上迭代删除列表中的项目时,我实际上切断了我所坐的分支。 您需要反向循环列表:
def deleteItemInList(alist, blist):
for i in range(len(alist) -1, -1, -1):
idx = alist[i]
del blist[idx]
您能展示一下实际的回溯吗?通常,迭代一个列表并同时修改它是一个糟糕的主意,而且通常最好构建一个新列表。@NightShadeQueen,而不是在循环中的那个点删除项目,我应该寻找我需要的所有其他元素,并将它们添加到一个新列表中。