if语句中多个条件的Python速记

2024-04-18 01:47:20 发布

您现在位置:Python中文网/ 问答频道 /正文

if x == y != z:
    print (x + y)

如果x==y和y!=z?它在我的代码中工作,但我不确定当多个条件不是全部==或时如何解释它们!=,或以上述后一种形式写出。你知道吗


Tags: 代码if条件形式print
1条回答
网友
1楼 · 发布于 2024-04-18 01:47:20

是的,如documentation中所述:

(...)

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).

因此您可以链接任何类型的比较器:<>==>=<=<>!=is [not][not] in。你知道吗

文件进一步使其更加正式:

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.

例如:

'a' in 'ab' in 'zabc'

相当于:

'a' in 'ab' and 'ab' in 'zabc'

相关问题 更多 >