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

alv*_*vas 19 python substring list 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
Run Code Online (Sandbox Code Playgroud)

输出:

this doesnt
@$  this sentences must be removed
this shouldnt
this isnt
#this should
this musnt
Run Code Online (Sandbox Code Playgroud)

期望的输出:

this doesnt
this shouldnt
this isnt
this musnt
Run Code Online (Sandbox Code Playgroud)

D.S*_*ley 32

简单的事情怎么样:

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


mjg*_*py3 13

这应该工作:

[i for i in sents if not ('@$\t' in i or '#' in i)]
Run Code Online (Sandbox Code Playgroud)

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

  • 我认为这个比其他两个好,因为不假设子串在开始时 (3认同)

cod*_*k3y 12

使用另一种技术 filter

filter( lambda s: not (s[0:3]=="@$\t" or s[0]=="#"), sents)
Run Code Online (Sandbox Code Playgroud)

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

合理?