【问题标题】:How to remove an element when I traverse a list遍历列表时如何删除元素
【发布时间】:2013-08-05 02:28:08
【问题描述】:

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

以此为例:

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

    使用list comprehension 而不是filter()

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

    或者,如果您想继续使用filter()

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

    【讨论】:

    • 交互式提示无需打印。
    • @BurhanKhalid Nah,但我喜欢添加它:)。呃,我还不如删了
    • 不打印,repr(x) 在交互式提示中打印。使用 print,将打印 str(x)。所以这取决于你想看到什么。 (尽管字符串列表无关紧要。)
    • @ChrisBarker 是的,列表不需要(至少是字符串列表):p
    【解决方案2】:

    列表推导是此循环的较短版本:

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

    请记住,这不会更改原始 colors 列表,它只会返回一个新列表,其中仅包含与您的过滤器匹配的项目。您可以删除匹配的项目,这将修改原始列表,但是您需要从末尾开始以避免连续匹配的问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-08
      • 2014-04-12
      • 2012-06-13
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 2013-06-23
      • 2018-06-27
      相关资源
      最近更新 更多