python list comprehension with a string

时间:2017-03-27 16:51:39

标签: python list-comprehension

我遇到了一个包含列表推导和字符串的有趣场景。以下是该场景的简化示例:

此:

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

返回:

ok

尽管' apple'出现在句子里。我是否错误地写了理解?如果有任何词语被禁止'是在'句子,' ok'不应该打印。

1 个答案:

答案 0 :(得分:2)

以下部分:

(not x in sentence for x in banned)

生成器表达式将被评估为True,无论内容是什么。

如果您想检查多个项目的真值,可能需要根据您的问题使用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')

正如@ Jean-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')