Fla*_*env 3 python operator-precedence
>>> "f" in "foo"
True
>>> "f" in "foo" == True
False
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么第二个表达式是 False。我看到==
优先级高于in
. 但随后我希望得到一个异常,这就是当我添加括号时会发生的情况:
>>> "f" in ("foo" == 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)
foo
似乎只有当位于 两侧时,表达式才为 True ==
,如下所示:
>>> "f" in "foo" == "foo"
True
>>> "f" in "foo" == "bar"
False
Run Code Online (Sandbox Code Playgroud)
我缺少什么?Python 在这里实际计算什么?
在 Python 中,比较运算符是链式的。
这就是为什么1 < 2 < 3 < 4
起作用并评估为 True 的原因。
请参阅https://docs.python.org/3/reference/expressions.html#comparisons
in
和==
都是这样的运算符,所以通过这种机制
"f" in "foo" == True
Run Code Online (Sandbox Code Playgroud)
方法
("f" in "foo") and ("foo" == True)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
58 次 |
最近记录: |