如果 value1 == value2 不是 python 中的 None,比较如何工作?
How does compare work if value1 == value2 is not None in python?
我发现
a == b is not None
比较a == b
,如果为真则执行b is not None
。
(a == b) is not None
和
a == (b is not None)
在哪里可以找到有关此类行为的更多信息?
这很简单,但我希望 True is not None
被执行
这在语言参考中有记载,6.10. Comparisons:
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c
have the interpretation that is conventional in mathematics:
comparison ::= or_expr (comp_operator or_expr)*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
Comparisons yield boolean values: True
or False
.
Comparisons can be chained arbitrarily, e.g., x < y <= z
is equivalent to x < y and y <= z
, except that y
is evaluated only once (but in both cases z
is not evaluated at all when x < y
is found to be false).
Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z
is equivalent to a op1 b and b op2 c and ... y opN z
, except that each expression is evaluated at most once.
Note that a op1 b op2 c
doesn’t imply any kind of comparison between a
and c
, so that, e.g., x < y > z
is perfectly legal (though perhaps not pretty).
==
和 is not
都是比较运算符,因此它们按上述方式链接。
我发现
a == b is not None
比较a == b
,如果为真则执行b is not None
。
(a == b) is not None
和
a == (b is not None)
在哪里可以找到有关此类行为的更多信息?
这很简单,但我希望 True is not None
被执行
这在语言参考中有记载,6.10. Comparisons:
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like
a < b < c
have the interpretation that is conventional in mathematics:comparison ::= or_expr (comp_operator or_expr)* comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in"
Comparisons yield boolean values:
True
orFalse
.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).Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then
a op1 b op2 c ... y opN z
is equivalent toa op1 b and b op2 c and ... y opN z
, except that each expression is evaluated at most once.Note that
a op1 b op2 c
doesn’t imply any kind of comparison betweena
andc
, so that, e.g.,x < y > z
is perfectly legal (though perhaps not pretty).
==
和 is not
都是比较运算符,因此它们按上述方式链接。