首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从列表中删除匹配子字符串的项目

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

Stack Overflow用户
提问于 2012-10-01 10:31:18
回答 3查看 49.3K关注 0票数 26

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

我尝试过使用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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-10-01 10:34:47

来点简单的,比如:

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

Stack Overflow用户

发布于 2012-10-01 10:37:14

这应该是可行的:

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

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

票数 16
EN

Stack Overflow用户

发布于 2012-10-01 10:45:17

另一种使用filter的技术

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

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

讲得通?

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12666897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档