如何使用if语句验证任何变量中是否包含任何值?我正在寻找类似的东西:
if "foo","bar","spam","eggs" in test1,test2:
Run Code Online (Sandbox Code Playgroud)
如果在任何test1,test2变量中找到四个值中的任何一个,则返回true.test1,test2应该是什么类型的?
稍后编辑:如果我有一个列表,那将会是这样的:
test1=['foo','abc','def']
if {'foo', 'bar', 'spam', 'eggs'} in test1
Run Code Online (Sandbox Code Playgroud)
您想使用集合交叉点:
if {test1, test2} & {'foo', 'bar', 'spam', 'eggs'}:
# true if there is an intersection between the two sets.
Run Code Online (Sandbox Code Playgroud)
所以,如果一个test1并test2设置为另一组中的四个值之一,该测试将是真实的.
如果您需要两者 test1并test2使用另一组中的值,则需要测试子集:
if {test1, test2} <= {'foo', 'bar', 'spam', 'eggs'}:
# true if all values in the first set are also in the second
Run Code Online (Sandbox Code Playgroud)