Searching for substring in element in a list an de

2019-02-23 16:53发布

问题:

I have a list and I am trying to delete the elements that have 'pie' in them. This is what I've done:

['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
    if "pie" in list[i]:
         del list[i]

I keep getting list index out of range, but when I change the del to a print statement it prints out the elements fine.

回答1:

Instead of removing an item from the list you're iterating over, try creating a new list with Python's nice list comprehension syntax:

foods = ['applepie','orangepie', 'turkeycake']
pieless_foods =  [f for f in foods if 'pie' not in f]


回答2:

Deleting an element during iteration, changes the size, causing IndexError.

You can rewrite your code as (using List Comprehension)

L = [e for e in L if "pie" not in e]


回答3:

Something like:

stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]

Modifying an object that you're iterating over should be considered a no-go.



回答4:

The reason to why you get a error is because you change the length of the list when you delete something!

Example:

first loop: i = 0, length of list will become 1 less because you delete "applepie" (length is now 2)
second loop: i = 1, length of list will now become just 1 because we delete "orangepie"
last/third loop: i = 2, Now you should see the problem, since i = 2 and the length of the list is only 1 (to clarify only list[0] have something in it!).

So rather use something like:

for item in in list:
    if "pie" not in item:
        new list.append(item)


回答5:

Another but longer way would be to note down the indexes where you encounter pie and delete those elements after the first for loop