比较可以任意链接,例如,
x < y <= z
等同于x < y and y <= z
,除了y
仅评估一次(但在两种情况下z
都没有被评估,当x < y
发现是假的时).
这些SO问题/答案对这种用法有了更多的了解:
所以像(人为的例子):
if 1 < input("Value:") < 10: print "Is greater than 1 and less than 10"
Run Code Online (Sandbox Code Playgroud)
只要求输入一次.这是有道理的.还有这个:
if 1 < input("Val1:") < 10 < input("Val2:") < 20: print "woo!"
Run Code Online (Sandbox Code Playgroud)
只询问Val2
是否 Val1
介于1和10之间,只打印"呜!" 如果 Val2
也是10到20之间(证明它们可以'任意链接').这也是有道理的.
但我仍然很好奇这是如何在词法分析器/解析器/编译器(或其他)级别实际实现/解释的.
上面的第一个例子基本上是这样实现的:
x = input("Value:")
1 < x and x < 10: …
Run Code Online (Sandbox Code Playgroud) 以下比较产生True
:
>>> '1' in '11'
True
>>> ('1' in '11') == True
True
Run Code Online (Sandbox Code Playgroud)
另一方面,使用括号,我得到一个TypeError:
>>> '1' in ('11' == True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
Run Code Online (Sandbox Code Playgroud)
那么我怎么False
没有括号?
>>> '1' in '11' == True
False
Run Code Online (Sandbox Code Playgroud)