我有一个包含值的列表:
['1', '3', '4', '4']
我有一个 if 语句,它会检查值是否包含在列表中,然后输出一个语句:
if "1" and "2" and "3" in columns:
print "1, 2 and 3"
考虑到列表不包含值“2”,它不应该打印语句,但是它是:
输出:
1, 2 and 3
有人能解释一下为什么会这样吗?是不是 Python 读取列表的方式导致了这种情况发生?
最佳答案
它按照 operator precedence 的顺序进行评估:
if "1" and "2" and ("3" in columns):
展开为:
if "1" and "2" and True:
然后计算 ("1"and "2")
给我们留下:
if "2" and True
最后:
if True:
相反,您可以检查字符串的集
是否是列
的子集:
if {"1", "2", "3"}.issubset(columns):
print "1, 2 and 3"
关于python - 如果语句检查列表包含在不应该返回 true 时返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31780687/