Python3中新函数(gt,ge,eq,le,lt)替代Python2中cmp()函数

Python3中已经不能使用cmp()函数了,被如下五个函数替代:

import operator       #首先要导入运算符模块
operator.gt(1,2)      #意思是greater than(大于)
operator.ge(1,2)      #意思是greater and equal(大于等于)
operator.eq(1,2)      #意思是equal(等于)
operator.le(1,2)      #意思是less and equal(小于等于)
operator.lt(1,2)      #意思是less than(小于)

operator.__lt__(a, b) 
operator.__le__(a, b) 
operator.__eq__(a, b) 
operator.__ne__(a, b) 
operator.__ge__(a, b) 
operator.__gt__(a, b)

lt(a, b) 相当于 a < b

le(a,b) 相当于 a <= b

eq(a,b) 相当于 a == b

ne(a,b) 相当于 a != b

gt(a,b) 相当于 a > b

ge(a, b)相当于 a>= b

函数的返回值不是布尔哦。这点需要注意,还是跟cmp一样返回的是数值

猜你喜欢

转载自blog.csdn.net/xc_zhou/article/details/81416742
今日推荐