Python中比较运算符的关联性 [英] Associativity of comparison operators in Python

查看:109
本文介绍了Python中比较运算符的关联性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中比较运算符的关联性是什么?进行三个比较很简单,但除此之外,我不确定它是如何做到的。它们似乎没有左右关联。

What is the associativity of comparison operators in Python? It is straightforward for three comparisons, but for more than that, I'm not sure how it does it. They don't seem to be right- or left-associative.

例如:

>>> 7410 >= 8690 <= -4538 < 9319 > -7092        
False    
>>> (((7410 >= 8690) <= -4538) < 9319) > -7092 
True

所以,不是左联想。

>>> 81037572 > -2025 < -4722 < 6493           
False
>>> (81037572 > (-2025 < (-4722 < 6493)))     
True

所以它也不是右关联的。

So it's not right-associative either.

我已经看到了一些链接的地方,但是如何进行四个或更多的比较?

I have seen some places that they are 'chained', but how does that work with four or more comparisons?

推荐答案

使用扩展了链式比较,因此:

Chained comparisons are expanded with and, so:

a <= b <= c

成为:

a <= b and b <= c

(不过, b 仅计算一次)比较语言参考中对此进行了解释。

(b is only evaluated once, though). This is explained in the language reference on comparisons.

请注意,惰性评估意味着<< c $ c> a> b ,结果为 False ,并且从未将 b c 。

Note that lazy evaluation means that if a > b, the result is False and b is never compared to c.

带括号的版本完全不同; a< =(b< = c)将评估 b< = c 然后比较 a 的结果,根本不涉及,因此比较结果以确定关联性是没有意义的。

Your versions with parentheses are completely different; a <= (b <= c) will evaluate b <= c then compare a to the result of that, and isn't involved at all, so it's not meaningful to compare the results to determine associativity.

这篇关于Python中比较运算符的关联性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆