【发布时间】:2011-08-14 18:06:28
【问题描述】:
我有一个元素列表,其中一些以“#”开头。我怎样才能删除这些元素? 我试过了:
content = [x for x in content[][0] if x != "#"]
但是:
content[][0]
似乎无效。最好的方法是什么?
【问题讨论】:
标签: python
我有一个元素列表,其中一些以“#”开头。我怎样才能删除这些元素? 我试过了:
content = [x for x in content[][0] if x != "#"]
但是:
content[][0]
似乎无效。最好的方法是什么?
【问题讨论】:
标签: python
content = [x for x in content if not x.startswith('#')]
【讨论】:
content[:] = [x for x in content if not x.startswith('#')]
使用python内置过滤方法也可以做到这一点:
content = filter(lambda x: not x.startswith('#'), content)
但请注意,在这两种情况下,您都没有删除 - 您正在创建一个新列表。
【讨论】:
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('#')]
【讨论】: