比较函数

来源:互联网 发布:js鼠标移开div消失 编辑:程序博客网 时间:2024/06/01 19:51

在Python2中用cmp函数。

cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。

>>> cmp(1,2)
-1
>>> cmp(3,2)
1
>>> cmp(5,5)
0


Python 3.X 的版本中已经没有 cmp 函数,如果你需要实现比较功能,需要引入 operator 模块,适合任何对象,包含的方法有:

operator.lt(a, b)operator.le(a, b)operator.eq(a, b)operator.ne(a, b)operator.ge(a, b)operator.gt(a, b)operator.__lt__(a, b)operator.__le__(a, b)operator.__eq__(a, b)operator.__ne__(a, b)operator.__ge__(a, b)operator.__gt__(a, b)
>>> import operator>>> operator.eq('hello', 'name');False>>> operator.eq('hello', 'hello');True

原创粉丝点击