Python | 浅学 | 7 NameError: name 'cmp' is not defined | AttributeError: module 'operator' has no attribute 'cmp'
Posted on 2022-07-02 16:59 董锡振 阅读(617) 评论(0) 编辑 收藏 举报
NameError: name 'cmp' is not defined
**报错原因:**因为python3.x中cmp函数去掉了,如果需要实现比较功能,那么可引入operator 模块,提供了6个比较运算符。gt lt ge eq le
import operator #首先要导入运算符模块operator # integers x,y = 100,200 print("x:",x, ", y:",y) print("operator.gt(x,y):", operator.gt(x,y)) #大于 False print("operator.gt(y,x):", operator.gt(y,x)) #大于 True # strings x,y = "A","B" print("x:",x, ", y:",y) print("operator.gt(x,y):", operator.gt(x,y)) #大于 False print("operator.gt(y,x):", operator.gt(y,x)) #大于 True # list list1, list2 = [1235, 'xyz'], [456, 'abc'] print("operator.gt(list1,list2):", operator.gt(list1,list2)) #大于 True print("operator.gt(list2,list1):", operator.gt(list2,list1)) #大于 False # printing the return type of the function print("type((operator.gt(x,y)):", type(operator.gt(x,y))) print(operator.lt(x,y)) #小于 print(operator.ge(x,y)) #大于等于 print(operator.eq(x,y)) #等于 print(operator.le(x,y)) #小于等于
本文来自博客园,作者:董锡振,转载请注明原文链接:https://www.cnblogs.com/dongxizhen/p/16437915.html