如何检查给定列表中的任意 3 个元素是否存在于字符串中。
例如——
words_to_check = ['apple', 'orange', 'banana', 'pear']
sample_string = 'apple, orange, and banana are fruits'
Answer - True
sample_string = 'apple and orange are fruits'
Answer - False (since only 2 elements match)
sample_string = 'apple, banana and pear are fruits'
Answer - True
sample_string = 'apple is a fruit'
Answer - False
我知道如果我想检查字符串是否包含列表中的任何 1 个元素,我可以执行以下操作 -
if any(fruit in sample_string for fruit in words_to_check):
print(sample_string)
我怎样才能对任何 3(或 n)个元素执行相同的操作?
我知道我可以使用 3 个 if 条件来做到这一点,但是有什么优雅/pythonic 的方法可以解决这个问题吗?
请您参考如下方法:
您可以使用以下方法:
>>> sample_string = 'apple, orange, and banana are fruits'
>>> len([True for fruit in words_to_check if fruit in sample_string])
3
