从列表中删除某些项目

时间:2015-08-02 11:51:44

标签: string list python-2.7

我正在研究如何从列表中删除特定项目。

"peppers", "cheese", "mushrooms", "bananas", "peppers"

我可以找到项目“辣椒”,并将其更改为“已消失!”,但我真的想删除该项目,使用

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

有人可以查看上面的代码并指出我出错的地方。

3 个答案:

答案 0 :(得分:3)

您可以使用列表推导。

def removeWord(needle, haystack):
    return [word for word in haystack if word.lower() != needle.lower()]

答案 1 :(得分:0)

要查找元素,请使用此功能。或者只是像往常一样定义它:

>>> 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']

答案 2 :(得分:0)

我终于明白了!在列表中迭代删除列表中的项目时,我实际上是在锯掉我正坐在的分支上。 您需要反向循环遍历列表:

def deleteItemInList(alist, blist):
    for i in range(len(alist) -1, -1, -1):
        idx = alist[i]
        del blist[idx]
相关问题