簡體   English   中英

從列表中刪除與子字符串匹配的項目

[英]Removing an item from list matching a substring

如果它與子字符串匹配,如何從列表中刪除元素?

我嘗試使用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

像這樣簡單的東西怎么樣:

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

這應該有效:

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

如果您只想要以指定句子開頭的內容,請使用str.startswith(stringOfInterest)方法

[i for i in sents if i.startswith('#')]

另一種使用filter的技術

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

您的原始方法的問題是,當您在列表項i上並確定它應該被刪除時,您將其從列表中刪除,這會將i+1項滑入i位置。 您在索引i+1處的循環的下一次迭代,但該項目實際上是i+2

說得通?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM