相关疑难解决方法(0)

Python中的链式比较实际上如何工作?

Python的文件进行比较说:

比较可以任意链接,例如,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)

python comparison-operators python-internals

9
推荐指数
1
解决办法
533
查看次数

python运算符的优先级和比较

以下比较产生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)

python

7
推荐指数
2
解决办法
1687
查看次数