从列表中删除与子字符串匹配的项目 [英] Removing an item from list matching a substring
本文介绍了从列表中删除与子字符串匹配的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果元素与子字符串匹配,如何从列表中将其删除?
How do I remove an element from a list if it matches a substring?
我尝试使用pop()
和enumerate
方法从列表中删除元素,但似乎我缺少一些需要删除的连续项目:
I have tried removing an element from a list using the pop()
and enumerate
method but seems like I'm missing a few contiguous items that needs to be removed:
sents = ['@$\tthis sentences needs to be removed', 'this doesnt',
'@$\tthis sentences also needs to be removed',
'@$\tthis sentences must be removed', 'this shouldnt',
'# this needs to be removed', 'this isnt',
'# this must', 'this musnt']
for i, j in enumerate(sents):
if j[0:3] == "@$\t":
sents.pop(i)
continue
if j[0] == "#":
sents.pop(i)
for i in sents:
print i
输出:
this doesnt
@$ this sentences must be removed
this shouldnt
this isnt
#this should
this musnt
所需的输出:
this doesnt
this shouldnt
this isnt
this musnt
推荐答案
简单的东西怎么样:
>>> [x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]
['this doesnt', 'this shouldnt', 'this isnt', 'this musnt']
这篇关于从列表中删除与子字符串匹配的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文