Liz*_*eiy 10 python if-statement list
我有一个包含值的列表:
['1', '3', '4', '4']
Run Code Online (Sandbox Code Playgroud)
我有一个if语句,它将检查列表中是否包含值然后输出一个语句:
if "1" and "2" and "3" in columns:
print "1, 2 and 3"
Run Code Online (Sandbox Code Playgroud)
考虑到列表不包含值"2",它不应该打印语句,但它是:
输出:
1, 2 and 3
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么会这样吗?这是Python读取列表的方式吗?
Kit*_*nde 35
它按运算符优先顺序进行评估:
if "1" and "2" and ("3" in columns):
Run Code Online (Sandbox Code Playgroud)
扩展到:
if "1" and "2" and True:
Run Code Online (Sandbox Code Playgroud)
然后评估("1" and "2")离开我们:
if "2" and True
Run Code Online (Sandbox Code Playgroud)
最后:
if True:
Run Code Online (Sandbox Code Playgroud)
相反,您可以检查set字符串是否是以下的子集columns:
if {"1", "2", "3"}.issubset(columns):
print "1, 2 and 3"
Run Code Online (Sandbox Code Playgroud)
gon*_*opp 11
为了理解发生的事情,要记住两条一般规则:
在计算表达式时"1" and "2" and "3" in columns,运算符优先级的顺序使其被计算为"1" and "2" and ("3" in columns).因此它被扩展为"1" and "2" and True,因为"3"它确实是一个元素columns(注意单引号或双引号对于python字符串是可互换的).
同一个框组中的操作员从左到右
由于我们有两个具有相同优先级的运算符,因此进行评估("1" and "2") and True.
表达式x和y首先计算x; 如果x为false,则返回其值; 否则,将评估y并返回结果值.
因此,("1" and "2") and True计算到"2" and True,然后评估为True.因此,你的if身体总是执行.