如果元素与子字符串匹配,如何从列表中删除该元素?
我尝试过使用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
发布于 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']
发布于 2012-10-01 10:37:14
这应该是可行的:
[i for i in sents if not ('@$\t' in i or '#' in i)]
如果只想要以指定句子开头的内容,请使用str.startswith(stringOfInterest)
方法
发布于 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
。
讲得通?
https://stackoverflow.com/questions/12666897
复制相似问题