2017-08-28 49 views
0

我有一個大名單,看起來是這樣的:從缺乏某些字符串列表中刪除元素 - 蟒蛇

entries = ["['stuff']...other stuff", "['stuff']...stuff", "['stuff']...more stuff", ...] 

我想刪除列表做的所有元素不包含單詞「其他」「東西」。

我試過,但它沒有消除所有我需要它(只有一些接近尾聲)的元素:

for e in entries: 
    if 'other' or 'things' not in e: 
     entries.remove(e) 
print entries 

我在做什麼錯?

+0

另外,請注意,[this](https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list)將是您的下一個bug ... –

+0

誰重新打開了這個?這顯然是[this]的重複**(https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) –

回答

1

在迭代它時,您不應該從列表中刪除項目。此外,您的條件聲明並不表達您的意思:它會檢查'other'的真實性,並且僅包含'things'。要修復它,請使用and和兩個單獨的in檢查。

如果列表不是很大,你可以只使用一個列表理解來重建它:

entries = [e for e in entries if "other" not in e and "things" not in e] 

否則,從列表開始的端部線圈和索引中刪除項目。

for i in range(len(entries)-1, -1, -1): 
    if "other" in entries[i] and "things" in entries[i]: 
     del entries[i] 
+1

嗯,兩個都很漂亮大問題。但問題的近因是有條件的。緊隨其後的是迭代過程中對列表的修改。爲了記錄,我沒有downvote ... –

0

正如其他人已經指出,在您的版本主要有三個問題:

for e in entries: 
    if 'other' or 'things' not in e: #or returns first truthy value, and `if other` is always true. Also, you need and, not or. 
     entries.remove(e) #mutating the item you are iterating over is bad 
print entries 

這裏是你的版本,修訂,以解決上述問題:

for e in words[:]: #words[:] is a copy of words, solves mutation issue while iterating 
    if 'other' not in e and 'things' not in e: #want words that both don't contain 'other' AND dont contain 'things' 
     print(e) 
     words.remove(e) 
print(words) 

而且這裏有一些替代方法可以做到這一點:

import re 

words = ['this doesnt contain chars you want so gone', 
     'this contains other so will be included', 
     'this is included bc stuff'] 

answer = list(filter(lambda x: re.search('other|stuff',x),words)) 
other_way = [sentence for sentence in words if re.search('other|stuff',sentence)] 

print(answer) 
print(other_way) 
+0

謹慎解釋downvote? – Solaxun

+0

我沒有downvote,但這個答案質量差。它只是提供了一種替代方法,其中*沒有解釋爲什麼原始方法是錯誤的,或者你的替代方案如何實際工作,如果問題是關於基本條件問題,那麼這將不會很有幫助。 –

0

您可以使用all(..)以檢查串作爲使用列表理解表達

>>> [entry for entry in entries if any(something in entry for something in ["other", "things"])] 

這將返回包含單詞的新列表或者「其他」或「東西」。