sap*_*api 10 python python-2.7
有人向我展示了这个奇怪的python语法示例.为什么[4]有效?
我原以为它要评估[5]或[6],两者都不起作用.是否有一些不成熟的过早优化?
In [1]: s = 'abcd'
In [2]: c = 'b'
In [3]: c in s
Out[3]: True
In [4]: c == c in s
Out[4]: True
In [5]: True in s
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-e00149345694> in <module>()
----> 1 True in s
TypeError: 'in <string>' requires string as left operand, not bool
In [6]: c == True
Out[6]: False
Run Code Online (Sandbox Code Playgroud)
Mos*_*she 13
这与允许python将多个运算符(如<)链接在一起的语法糖相同.
例如:
>>> 0 < 1 < 2
True
Run Code Online (Sandbox Code Playgroud)
这相当于(0<1) and (1<2),只有中间表达式只被评估一次.
该陈述c == c in s同样等同于(c == c) and (c in s),其评估结果为True.
要突出显示前一点,中间表达式仅评估一次:
>>> def foo(x):
... print "Called foo(%d)" % x
... return x
...
>>> print 0 < foo(1) < 2
Called foo(1)
True
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅Python语言参考.