【问题标题】:remove all list elements starting with a hash删除所有以哈希开头的列表元素
【发布时间】:2011-08-14 18:06:28
【问题描述】:

我有一个元素列表,其中一些以“#”开头。我怎样才能删除这些元素? 我试过了:

content = [x for x in content[][0] if x != "#"]

但是:

content[][0]

似乎无效。最好的方法是什么?

【问题讨论】:

    标签: python


    【解决方案1】:
    content = [x for x in content if not x.startswith('#')]
    

    【讨论】:

    • 就地方法:content[:] = [x for x in content if not x.startswith('#')]
    • @Manny D - 是的,这是一个很好的补充。
    【解决方案2】:

    使用python内置过滤方法也可以做到这一点:

    content = filter(lambda x: not x.startswith('#'), content)
    

    但请注意,在这两种情况下,您都没有删除 - 您正在创建一个新列表。

    【讨论】:

      【解决方案3】:
      skip_char = ('!!','==','**','#')
      result[:] = [item for item in content if not item.startswith(skip_char)]
      

      删除或跳过所有以 # 和 !! 开头的列表元素或项目和 == 和 **。 您可以作为 tuple 传递,以便将来在跳过部分进行更改。

      或在一行中添加多个条件以删除以“!! and == and ** and #”开头的项目

      [item for item in content if not item.startswith('!!') and not item.startswith('==') and not item.startswith('**') and not item.startswith('#')]
      

      【讨论】:

        猜你喜欢
        • 2011-11-17
        • 2011-03-27
        • 1970-01-01
        • 2013-11-09
        • 1970-01-01
        • 2017-05-20
        • 2015-03-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多