如果匹配子字符串,我如何從列表中刪除元素?從匹配子字符串的列表中刪除項目 - Python
我曾嘗試使用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
經常從列表中刪除項目,而您正在迭代該列表。閱讀與此相關的其他數十個Stack Overflow問題。另請參閱[文檔中的註釋](http://docs.python.org/reference/compound_stmts.html#for)。 –
您應該始終避免在迭代容器時更改容器的長度,這是容災 – wim
通常,創建新的過濾列表通常比嘗試就地修改列表更好。不可變的算法總是比較容易理解(雖然並不總是比較容易理解如何編寫)。當你只是替換值時,有時候就地工作的效率提高了,但是當你刪除或插入列表的中間時,通常會獲得_worse_效率以及不太穩健的邏輯。 – abarnert