Hello 大家好,今天给大家介绍 Python 中用于比较运算的运算符重载。这些方法分别是:
object.__lt__(self, other)
# 小于(<)运算object.__le__(self, other)
# 小于等于(<=)运算object.__eq__(self, other)
# 等于(==)运算object.__ne__(self, other)
# 不等于(!=)运算object.__gt__(self, other)
# 大于(>)运算object.__ge__(self, other)
# 大于等于(>=)运算
带双下划线的函数在 Python 中称为特殊方法,在进行某些操作时,它们会被 Python 自动调用,如果你还对 Python 数据模型不了解的话,可以参考官方文档中的 Python 数据模型 章节。不过不了解也没关系,不影响你往下看。
假设一个苹果销售商给你提了一个需求,他们有很多苹果要售卖。销售商想将所有的苹果按重量从大到小排序,但是因为苹果太多,不可能人工去排序。每个苹果在入库时都称了重量,而且贴上了编号,且都输入了计算机存档。所以现在只差你对他们进行排序了。
你可能立马就想动手写个排序的程序,专门来给苹果排序。这在其他语言中这么做很正常,但 Python 的妙处就在于语言本身就有很多特性(Python 数据模型提供的特性),我们根本不需要自己写排序的算法就可以完成这个任务。我们想要将 Python 的能力发挥到极致,就要利用其性质,让自己的代码 Pythonic 起来。
在解决这个问题之前,我们来看看 Python 怎么对列表中的数字进行排序:
>>> nums = [1, 94, 2, 4, 6, 3, 2, 6, 32]
>>> sorted(nums, reverse=True)
[94, 32, 6, 6, 4, 3, 2, 2, 1]
Python 内置函数 sorted
可以对列表进行排序。那么对苹果列表能不能排序呢。
首先我们来定义一个苹果类,它有两个属性分别是重量(克)和编号:
class Apple:
def __init__(self, weight, code):
self.weight = weight;
self.code = code;
据此我们可以创建 Apple 类的对象:
apple = Apple(256, 0)
接着,我们可以实现苹果类中的特殊方法:
class Apple:
def __init__(self, weight, code):
self.weight = weight
self.code = code
def __lt__(self, other):
return self.weight < other.weight
def __le__(self, other):
return self.weight <= other.weight
def __eq__(self, other):
return self.weight == other.weight
def __ne__(self, other):
return self.weight != other.weight
def __gt__(self, other):
return self.weight > other.weight
def __ge__(self, other):
return self.weight >= other.weight
def __repr__(self):
return '({},{})'.format(self.weight, self.code)
我们实现了六个比较运算符号,和一个用于提供对象字符串表示的特殊方法。现在我们可以创建两个苹果来比较一下大小:
apple1 = Apple(240, 0)
apple2 = Apple(120, 1)
print(apple1 < apple2) # False
现在,我们可以借助 Python 内置的 sorted
函数对苹果列表进行排序:
# 创建 10 个重量值,重量为 [1, 501) 范围内的随机整数
weights = random.sample(range(1, 501), 10)
# 创建由 10 个 (重量, 编号)对组成的列表
apple_data = zip(weights, range(10))
# 创建 10 个苹果对象
apples = [Apple(d[0], d[1]) for d in apple_data]
print('排序前:')
print(apples)
sorted(apples)
print('排序后:')
print(apples)
上面的代码输出如下:
排序前:
[(262,0), (148,1), (364,2), (426,3), (326,4), (88,5), (466,6), (85,7), (298,8), (136,9)]
排序后:
[(85,7), (88,5), (136,9), (148,1), (262,0), (298,8), (326,4), (364,2), (426,3), (466,6)]
上面的代码很简单,所以说 Python 的编程思想就是尽量的使用 Python 数据模型所提供的功能,这样才能更加高效和优雅地使用 Python。
近期文章:
Python 每一天 (5.16) - Emoji
Python 每一天 (5.15) - Counter 类
Python 每一天(5.14) - 字符串的 stirp 函数
Python札记8:什么是first-class function?
Python札记6:with与上下文管理器
我的知乎:谢添鑫
欢迎关注微信公众号:小鑫的代码日常
欢迎加入Python学习交流群:532232743,一起学习,一起快乐~