2017-03-27 81 views
0

我遇到了一個有趣的腳本與列表解析和字符串。下面是場景的一個簡單的例子:python列表理解與字符串

此:

banned = ['apple', 'pear'] 
sentence = 'I will eat an apple'  
if(not x in sentence for x in banned): print('ok') 

返回:

ok 

雖然 '蘋果' 出現在句子。我錯誤地寫了理解嗎?如果'禁止'中的任何詞語在'句子'中,則'不能打印'。

+1

非空列表(無論值)是truthy – FamousJameous

+7

你'all'關鍵字之後是 - '如果所有(在不禁止在句子X的X):打印( 'OK')' – asongtoruin

+1

如果你使用'x不在句子' – barny

回答

1

以下部分:

(not x in sentence for x in banned) 

是發電機表達式將被評估爲真,而不管任何含量。

如果你想檢查多個項目的真值,你可能想要根據你的問題使用anyall函數。

在這種情況下,它似乎是你需要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將檢查成員的整個字符串內,而不是它的話。也就是說,如果輸入字符串中的某個單詞包含banned列表中的單詞,它將返回True。像pearl這是包含字pear

解決該問題的一種方法是檢查拆分文本中的成員資格或使用正則表達式。

另一種方法是使用set和路口:

banned = {'apple', 'pear'} # use set instead of list 
sentence = 'I will eat an apple' 
if banned.intersection(sentence.split()): 
    print('ok') 

正如@讓FrançoisFabre提到最好使用set.isdisjoint()而非set.intersection因爲你只是要檢查的交集。

banned = {'apple', 'pear'} # use set instead of list 
sentence = 'I will eat an apple' 
if not banned.isdisjoint(sentence.split()): 
    print('ok') 
+0

'if banned.intersection(sentence.split()):'創建'set',這是浪費。更好地使用'not banned.isdisjoint()'作爲條件。 –

+0

@ Jean-FrançoisFabre'isdisjoint()'不會爲這個問題返回正確的結果。嘗試'banned.isdisjoint('apple pear banana'.split())'。 – Kasramvd

+0

我寫了'not {'apple','pear'}。isdisjoint('apple pear banana'.split())'。不isdisjoint意味着交集不是空的。這樣可行。 –