次の部分:
(not x in sentence for x in banned)
にかかわらず、コンテンツが何であれの、Trueとして評価されるジェネレータ式です。
複数の項目の真理値をチェックする場合は、問題に応じてany
またはall
のいずれかの機能を使用することができます。
あなたがall()
が必要と思われる。この場合:
banned = ['apple', 'pear']
sentence = 'I will eat an apple'
if all(x not in sentence for x in banned):
print('ok')
または、一部x not in sentence
は文字列全体ではなく、その言葉の中にメンバーシップをチェックすることに注意してください。つまり、入力文字列内の単語の1つにbanned
の単語が含まれている場合はTrueを返します。単語pear
を含むpearl
のように。
この問題を回避する1つの方法は、分割されたテキストのメンバーシップをチェックするか、正規表現を使用することです。
もう一つの選択肢は、set
との交点を使用して次のようになります。ジャンFrançoisFabreが、それはあなたがちょうど交差点を確認したいので、set.isdisjoint()
ではなくset.intersection
を使用することをお勧めします言及
banned = {'apple', 'pear'} # use set instead of list
sentence = 'I will eat an apple'
if banned.intersection(sentence.split()):
print('ok')
@として。
banned = {'apple', 'pear'} # use set instead of list
sentence = 'I will eat an apple'
if not banned.isdisjoint(sentence.split()):
print('ok')
非空のリストは、(どんな値)あなたは 'ALL'キーワードの後にしているtruthy – FamousJameous
ある - 'すべての場合(禁止中のxについての文章ではないのx):プリント( 'OK') ' – asongtoruin
'x not in sentence'を使った方が少しはっきりしています – barny