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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12666897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:33:41  来源:igfitidea点击:

Removing an item from list matching a substring

pythonlistsubstringstring-matching

提问by alvas

How do I remove an element from a list if it matches a substring?

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

I have tried removing an element from a list using the pop()and enumeratemethod but seems like I'm missing a few contiguous items that needs to be removed:

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

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

Output:

输出:

this doesnt
@$  this sentences must be removed
this shouldnt
this isnt
#this should
this musnt

Desired output:

期望的输出:

this doesnt
this shouldnt
this isnt
this musnt

采纳答案by D.Shawley

How about something simple like:

简单的事情怎么样:

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

回答by mjgpy3

This should work:

这应该有效:

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

If you want only things that begin with those specified sentential use the str.startswith(stringOfInterest)method

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

回答by cod3monk3y

Another technique using filter

另一种技术使用 filter

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

The problem with your orignal approach is when you're on list item iand determine it should be deleted, you remove it from the list, which slides the i+1item into the iposition. The next iteration of the loop you're at index i+1but the item is actually i+2.

您的原始方法的问题在于,当您在列表项上i并确定应将其删除时,您将其从列表中删除,从而将i+1项目滑入该i位置。您在 index 处的循环的下一次迭代,i+1但该项目实际上是i+2.

Make sense?

有道理?