问题描述
我正在基于lemmatization编写简单的分类器,本质上,我需要检查元组是否包含列表中的任何元素。简单的例子:
>>> ['dog','bone'] in ('dog','cat','parrot')
返回False
,而我需要它返回True
。最简单,最优雅的方法是什么?
解决方法
要么:
any([val in ('dog','cat','parrot') for val in ['dog','bone']])
对于实际用法,请不要在理解中声明列表和元组,因为它会无故浪费资源,您应该:
test_list = ['dog','bone']
available_items = ('dog','parrot')
any([val in available_items for val in test_list])
另一个可能的解决方案:
set(['dog','bone']).intersection(set(('dog','parrot'))) # Would return a non empty set if there is an intersection,which translates to true.
# Use case:
if set(['dog','parrot'))):
print('intersection!')