问题
I recently discovered that the following returns True
:
'a' in 'ab' in 'abc'
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.
Is this an accidental feature in the implementation of CPython, or is this behaviour specified?
回答1:
This is fully specified behaviour, not an accidental feature. Operator chaining is defined in the Comparison operators section:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
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.
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.
来源:https://stackoverflow.com/questions/38296689/where-in-the-python-docs-does-it-allow-the-in-operator-to-be-chained