热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python3 cmp实现方式

python3 cmp实现方式-目录python3cmp实现PY3__cmp__mixin类cmp()函数实现的注解python3使用cmp函数报错使用operator模块pyth

python3 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(小于)

PY3__cmp__ mixin类

import sys
PY3 = sys.version_info[0] >= 3
if PY3:
    def cmp(a, b):
        return (a > b) - (a  0
        def __lt__(self, other):
            return self.__cmp__(other) <0
        def __ge__(self, other):
            return self.__cmp__(other) >= 0
        def __le__(self, other):
            return self.__cmp__(other) <= 0
else:
    class PY3__cmp__:
        pass
class YourClass(PY3__cmp__):
	'''自定义类,可以用list.sort函数或者sorted函数来实现排序。'''
	def __init__(self, name, age):
        self.name = name
        self.age = age
    def __cmp__(self, other):
        return cmp(self.age, other.age)

cmp()函数实现的注解

bool仅仅是一个int子类,那么True和False可以理解为1和0区别。

因为如果第一个参数小于第二个参数,cmp返回负值,如果参数相等则返回0,否则返回正值,可以看到False - False == 0,True - False == 1和False - True == -1为cmp提供正确的返回值。

python3 使用cmp函数报错

python3中已经不使用cmp函数进行比较大小

使用operator模块

import operator
lt(a,b) 相当于 ab 
ge(a,b)相当于 a>=b

函数的返回值是布尔哦


推荐阅读
author-avatar
jackystorm岁月_657
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有