从匹配子字符串的列表中删除项目

时间:2012-10-01 02:31:18

标签: python list substring string-matching

如果元素与子字符串匹配,如何从列表中删除元素?

我尝试使用pop()enumerate方法从列表中删除元素,但似乎我缺少一些需要删除的连续项:

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

3 个答案:

答案 0 :(得分:27)

如此简单的事情:

>>> [x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]
['this doesnt', 'this shouldnt', 'this isnt', 'this musnt']

答案 1 :(得分:12)

这应该有效:

[i for i in sents if not ('@$\t' in i or '#' in i)]

如果您只想要以指定句子开头的内容使用str.startswith(stringOfInterest)方法

答案 2 :(得分:11)

使用filter

的另一种技巧
filter( lambda s: not (s[0:3]=="@$\t" or s[0]=="#"), sents)

您的orignal方法的问题是当您在列表项i上并确定它应该被删除时,您将其从列表中删除,这会将i+1项目滑动到{{1位置。循环的下一次迭代,你在索引i,但该项实际上是i+1

有意义吗?