Python 如何在遍历列表时删除元素

Python 如何在遍历列表时删除元素,python,Python,我在《如何在遍历列表时删除元素》中读到了这一点: 以此为例: >>> colors=['red', 'green', 'blue', 'purple'] >>> filter(lambda color: color != 'green', colors) ['red', 'blue', 'purple'] 但是如果我想删除作为字符串一部分的元素,我该怎么做呢? i、 e如果我只输入'een'(只是'green'字符串元素颜色的一部分?使用a而不是使用过滤器

我在《如何在遍历列表时删除元素》中读到了这一点:

以此为例:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
但是如果我想删除作为字符串一部分的元素,我该怎么做呢? i、 e如果我只输入'een'(只是'green'字符串元素颜色的一部分?

使用a而不是使用
过滤器()

或者,如果要继续使用
过滤器()


列表理解是此循环的较短版本:

new_list = []
for i in colors:
   if 'een' not in i:
       new_list.append(i)
以下是列表:

new_list = [i for i in colors if 'een' not in i]
您还可以使用过滤器示例,如下所示:

>>> filter(lambda x: 'een' not in x, colors)
['red', 'blue', 'purple']
请记住,这不会更改原始的
颜色
列表,它只会返回一个新列表,其中只包含与您的筛选器匹配的项目。您可以删除匹配的项目,这将修改原始列表,但您需要从头开始,以避免出现连续匹配的问题:

for i in colors[::-1]: # Traverse the list backward to avoid skipping the next entry.
    if 'een' in i:
       colors.remove(i)

不需要在交互提示上打印。@BurhanKhalid-Nah,但我喜欢添加它:)。呃,我也可以在不打印的情况下删除它,
repr(x)
会在交互提示中打印出来。使用print时,
str(x)
被打印。所以这取决于你想看什么。(虽然这对于字符串列表并不重要。)@ChrisBarker Yea,对于列表(至少是字符串列表)不是必需的:p
>>> filter(lambda x: 'een' not in x, colors)
['red', 'blue', 'purple']
for i in colors[::-1]: # Traverse the list backward to avoid skipping the next entry.
    if 'een' in i:
       colors.remove(i)