python cmp()_Python cmp() 函数

Python cmp() 函数

描述

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

语法

以下是 cmp() 方法的语法:

cmp( x, y )

参数

x:数值表达式。

y:数值表达式。

返回值

如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。

实例

以下展示了使用 cmp() 方法的实例:

#!/usr/bin/python

print "cmp(80, 100) : ", cmp(80, 100)

print "cmp(180, 100) : ", cmp(180, 100)

print "cmp(-80, 100) : ", cmp(-80, 100)

print "cmp(80, -100) : ", cmp(80, -100)

以上实例运行后输出结果为:

cmp(80, 100) : -1

cmp(180, 100) : 1

cmp(-80, 100) : -1

cmp(80, -100) : 1

拓展

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值