遍历列表以查找if语句中的子字符串



我有一个字符串列表:

relations = ['displays', '1000displays', 'chooses', '1011chooses', '1020displays', 'clicks', '1031clicks', 'add to', 'checks', '1040checks', 'inserts discount offer to', '1050inserts discount offer to', 'inserts']

和一个子字符串:

t_object = 'discount offer'

只有当字符串discount offer不在relations列表中时,我才想执行if块中的代码。

我有以下代码,但由于discount offer存在于relations中,它不应该进入if语句中的代码块,但它确实进入了。为什么?

if len(t_object) > len(objects[sentence_number]) and (s for s in relations if t_object not in s):
print('I am in but I shoudlt be.')

使用any()函数。

if len(t_object) > len(objects[sentence_number]) and not any(t_object in s for s in relations):

最新更新