问题描述
我最近发现以下内容返回True
:
I recently discovered that the following returns True
:
'a' in 'ab' in 'abc'
我知道python比较链,例如a < b < c
,但是我在文档中看不到任何合法的内容.
I'm aware of the python comparison chaining such as a < b < c
, but I can't see anything in the docs about this being legal.
这是CPython实现中的偶然功能,还是指定了此行为?
Is this an accidental feature in the implementation of CPython, or is this behaviour specified?
推荐答案
这是完全指定的行为,不是偶然的功能.运算符链接在 比较运算符部分中定义:
This is fully specified behaviour, not an accidental feature. Operator chaining is defined in the Comparison operators section:
in
是比较运算符之一;来自同一部分:
in
is one of the comparison operators; from the same section:
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
| "is" ["not"] | ["not"] "in"
对于可能没有太大意义的组合,没有例外.
No exceptions are made for combinations that may not make much sense.
因此,您作为示例使用的特定表达式将作为'a' in 'ab' and 'ab' in 'abc'
执行,而'ab'
文字仅被执行(加载)一次.
The specific expression you used as an example is thus executed as 'a' in 'ab' and 'ab' in 'abc'
, with the 'ab'
literal only being executed (loaded) once.
这篇关于允许在python文档中的"in"运算符链接的地方吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!