验证任何集中是否存在任何值

时间:2015-07-18 13:46:51

标签: python

如何使用if语句验证任何变量中是否包含任何值?我正在寻找类似的东西:

if "foo","bar","spam","eggs" in test1,test2:

如果在任何test1,test2变量中找到四个值中的任何一个,则返回true。 test1,test2应该是什么类型的?

稍后编辑: 如果我有一个列表,那将会是这样的:

test1=['foo','abc','def']
if {'foo', 'bar', 'spam', 'eggs'} in test1

2 个答案:

答案 0 :(得分:8)

您想使用set intersections

if {test1, test2} & {'foo', 'bar', 'spam', 'eggs'}:
    # true if there is an intersection between the two sets.

因此,如果test1test2中的一个设置为另一个中的四个值之一,则测试将为真。

如果您需要 test1test2来使用其他集合中的值,则需要测试子集:< / p>

if {test1, test2} <= {'foo', 'bar', 'spam', 'eggs'}:
    # true if all values in the first set are also in the second

答案 1 :(得分:2)

您可以在any()内置函数中使用生成器表达式:

any(i in j for j in [test1,test2] for i in my_var)

样本:

>>> my_var={"foo","bar","spam","eggs"}
>>> test1={'a','b'}
>>> test2={'c','d'}
>>> 
>>> any(i in j for j in [test1,test2] for i in my_var)
False
>>> test2={'c','foo'}
>>> any(i in j for j in [test1,test2] for i in my_var)
True
相关问题