Python 3中实现cmp()函数的功能

cmp() 函数是Python 2中的一个用于比较两个列表, 数字或字符串等的大小关系的函数, 在Python 3中已经无法使用这个函数了:

>>> a = [1, 2, 3] 
>>> b = [4, 5, 6] 
>>> cmp(a, b) Traceback (most recent call last): File "<pyshell#60>", line 1, in <module> cmp(a, b) NameError: name 'cmp' is not defined 
>>>

在Python 3中, 使用operator模块来实现同样的功能. 无论是在交互模式还是在文本模式下, 要使用operator模块都需要先导入该模块:

import operator

在交互式模式下可以这样使用:

>>> a = [1, 2] 
>>> b = [1, 3] 
>>> import operator 
>>> operator.eq(a, b) 
False 
>>>

但是如果我们在文本模式下也这样使用:

a = [1, 2] 
b = [1, 3] 
import operator 
operator.eq(a, b)

Run之后并没有任何回显:

=================== RESTART: C:/Users/Master/Desktop/1.py =================== 
>>>

如果要实现交互式模式下一样的回显, 需要使用print()函数输出:

a = [1, 2] 
b = [1, 3] 
import operator 
print(operator.eq(a, b))

回显如下:

=================== RESTART: C:/Users/Master/Desktop/1.py ===================
False
>>>

operator模块的功能如下:

函数
含义
operator.lt(a, b)
a < b
operator.le(a, b)
a <= b
operator.eq(a, b)
a == b
operator.ne(a, b)
a != b
operator.gt(a, b)
a > b
operator.ge(a, b)
a >= b

比较大小的规则是以ASCII码表为基准, 从两个列表中的第一个字符开始进行比较, 返回值为布尔类型.


荒原之梦网全部内容均为原创,提供了涵盖考研数学基础知识、考研数学真题、考研数学练习题和计算机科学等方面,大量精心研发的学习资源。

意见反馈 | 内容纠错 | 微信 | QQ | 公众号 | 知乎 | 微博 | 博客园 |CSDN | B 站 | 电子邮件
豫 ICP 备 17023611 号-1 | 公网安备 - 荒原之梦 豫公网安备 41142502000132 号 | SiteMap
Copyright © 2017-2024 ZhaoKaifeng.com 版权所有 All Rights Reserved.

Copyright © 2024   zhaokaifeng.com   All Rights Reserved.
豫ICP备17023611号-1
 豫公网安备41142502000132号

荒原之梦 自豪地采用WordPress