2

我阅读了如何在遍历列表时删除元素: Remove elements as you traverse a list in Python

以此为例:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']

但是,如果我想删除该元素(如果它是字符串的一部分),我该怎么做?即如果我只输入'een',我想过滤'green'(只是颜色中'green'字符串元素的一部分?

4

2 回答 2

5

Use a list comprehension instead of using filter():

>>> colors = ['red', 'green', 'blue', 'purple']
>>> [color for color in colors if 'een' not in color]
['red', 'blue', 'purple']

Or, if you want to continue using filter():

>>> filter(lambda color: 'een' not in color, colors)
['red', 'blue', 'purple']
于 2013-08-04T06:15:28.180 回答
3

A list comprehension is a shorter version of this loop:

new_list = []
for i in colors:
   if 'een' not in i:
       new_list.append(i)

Here is the list comprehension equivalent:

new_list = [i for i in colors if 'een' not in i]

You can also use the filter example, like this:

>>> filter(lambda x: 'een' not in x, colors)
['red', 'blue', 'purple']

Keep in mind this won't change the original colors list, it will just return a new list with only the items that match your filter. You can remove the items that match which will modify the original list, however you need to start from the end to avoid problems with consecutive matches:

for i in colors[::-1]: # Traverse the list backward to avoid skipping the next entry.
    if 'een' in i:
       colors.remove(i)
于 2013-08-04T06:27:28.377 回答