2017-08-28 4 views
0

私は次のようになります大規模なリストがあります:削除する要素 - のpython

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)はあなたの次のバグになります。 –

+0

誰がこれを再開したのですか?これは**明らかに[this](https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values)の重複**です –

答えて

1

繰り返し処理中にリストから項目を削除しないでください。また、条件文はあなたが意味することをしません。'other'の真実性をチェックし、包含のためには'things'のみをチェックします。これを修正するには、andに2つの別々のinチェックを使用してください。

リストは非常に大きいではない場合、あなたはそれを再構築するために、リストの内包表記を使用することができます、それ以外の場合は

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

先頭に、リストの末尾からのループとインデックスで項目を削除します。

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) 

そして:

ここ
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 i in range(len(entries)-1, -1, -1): 
    if "other" in entries[i] and "things" in entries[i]: 
     del entries[i] 
+1

まあ、どちらも可愛いです大きな問題。しかし、問題の根本原因は条件付きです。そして、後ろには、反復中のリストの変更があります。記録のために、私はdownvoteをしなかった... –

0

、お使いのバージョンでは三つの主要な問題がありますこれを行う別の方法は次のとおりです。

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"])] 

関連する問題