Python3自定义排序与运算符重载详解
本文详解Python3中自定义排序的两种实现方式:通过functools.cmp_to_key使用cmp函数,以及重写类的比较运算符(__lt__等)。文章对比了Python2与Python3的差异,提供了基于二维点的排序示例及完整代码,帮助开发者掌握Python3中的排序技巧。
Python3自定义排序与运算符重载详解
Python3相较于Python2在功能实现上存在诸多差异。
在Python2版本中,开发者可以直接定义一个cmp函数作为参数传入sort方法来实现自定义排序逻辑,然而这一特性在Python3中已被移除。
本文旨在总结Python3中实现自定义排序的两种主要写法,欢迎读者补充其他方案。
为了演示排序逻辑,我们选取二维空间中的点作为待排序的数据结构,目标是实现先比较x坐标,再比较y坐标的排序规则。
class Pos:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return ('(%s, %s)' % (self.x, self.y))
__repr__ = __str__方法一:使用cmp函数
第一种方法依然采用重写cmp函数或lambda表达式的形式,这与Python2的实现方式非常相似。
需要注意的是,直接使用sorted函数配合此方法无法成功完成排序。
必须借助functools模块进行转换。
import functools
def cmp(a, b):
return a.x-b.x if a.x != b.x else a.y-b.y # x y均按照从小到大的顺序
if __name__ == '__main__':
test_list = [Pos(5, 1), Pos(2,5), Pos(2, 4)]
# test_list.sort(key=functools.cmp_to_key(lambda a,b: a.x-b.x if a.x != b.x else a.y-b.y))
test_list.sort(key=functools.cmp_to_key(cmp))
# sorted(test_list, key=functools.cmp_to_key(cmp)) # 亲测此方法不能成功排序
print(test_list) # 输出结果 [(2, 4), (2, 5), (5, 1)]方法二:重写类比较方法
在Python2中,开发者可以直接重写__cmp__方法来实现对象间的比较,但该机制在Python3中已被取消。
在Python3中,需要分别实现各个比较运算符对应的魔法方法。
__lt__: <
__gt__: >
__ge__: >=
__eq__: ==
__le__: <=具体实现代码如下。
class Pos:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return ('(%s, %s)' % (self.x, self.y))
def __lt__(self, other):
print('lt: ' + str(self))
return self.x < other.x if self.x != other.x else self.y < other.y
def __gt__(self, other):
print('gt: ' + str(self))
return self.x > other.x if self.x != other.x else self.y > other.y
def __ge__(self, other):
print('ge: ' + str(self))
return self.x >= other.x if self.x != other.x else self.y >= other.y
def __eq__(self, other):
print('eq: ' + str(self))
return self.x == other.x and self.y == other.y
def __le__(self, other):
print('le: ' + str(self))
return self.x <= other.x if self.x != other.x else self.y <= other.y
__repr__ = __str__接下来进行实际测试验证。
if __name__ == '__main__':
if Pos(5,1) <= Pos(2,4):
print('True!')
if Pos(5,1) == Pos(2,4):
print('True!')
if Pos(5,1) > Pos(2,4):
print('True!')
# 输出
# le: (5, 1)
# eq: (5, 1)
# gt: (5, 1)
# True!最后,我们将上述方法应用于实际的排序操作中。
if __name__ == '__main__':
test_list = [Pos(5, 1), Pos(2,5), Pos(2, 4)]
test_list.sort()
print(test_list)
test_list.sort(reverse=True)
print(test_list)
# 输出
# lt: (2, 5)
# lt: (2, 4)
# [(2, 4), (2, 5), (5, 1)]
# lt: (2, 5)
# lt: (2, 4)
# [(5, 1), (2, 5), (2, 4)]Python3中多种排序方法的实现
# coding=gbk
import random
from array import array
def swap(lyst,i,j):
temp = lyst[i]
lyst[i] = lyst[j]
lyst[j] = temp
#选择排序,复杂度O(n^2)
def selectionSort(lyst):
i = 0
while i < len(lyst) - 1:
minIndex = i
j = i + 1
while j < len(lyst):
if lyst[j] < lyst[minIndex]:
minIndex = j
j += 1
if minIndex != i:
swap(lyst,minIndex,i)
i += 1
#冒泡排序,复杂的O(n^2)
def bubbleSort(lyst):
n = len(lyst)
while n > 1:
i = 1
while i < n:
if lyst[i] < lyst[i-1]:
swap(lyst,i,i-1)
i += 1
n -= 1
#冒泡排序优化改进最好情况
def bubbleSortWithTweak(lyst):
n = len(lyst)
while n > 1:
swapped = False
i = 1
while i < n:
if lyst[i] < lyst[i-1]:
swap(lyst,i,i-1)
swapped = True
i += 1
if not swapped: return
n -= 1
#插入排序,复杂的O(n^2)
def insertionSort(lyst):
i = 1
while i < len(lyst):
itemToInsert = lyst[i]
j = i - 1
while j >= 0:
if itemToInsert < lyst[j]:
lyst[j+1] = lyst[j]
j -= 1
else:
break
lyst[j+1] = itemToInsert
i += 1
#快速排序,最好情况,复杂的O(n*(log2 n)),最坏情况,复杂的O(n^2)
def quicksort(lyst):
quicksortHelper(lyst,0,len(lyst)-1)
def quicksortHelper(lyst,left,right):
if left < right:
pivotLocation = partition(lyst,left,right)
quicksortHelper(lyst,left,pivotLocation-1)
quicksortHelper(lyst,pivotLocation+1,right)
def partition(lyst,left,right):
middle = (left+right) // 2
pivot = lyst[middle]
lyst[middle] = lyst[right]
lyst[right] = pivot
boundary = left
for index in range(left,right):
if lyst[index] < pivot:
swap(lyst,index,boundary)
boundary += 1
swap(lyst,right,boundary)
return boundary
#合并排序
def mergeSort(lyst):
copyBuffer = [0]*(len(lyst))
mergeSortHelper(lyst,copyBuffer,0,len(lyst)-1)
def mergeSortHelper(lyst,copyBuffer,low,high):
if low < high:
middle = (low+high)//2
mergeSortHelper(lyst,copyBuffer,low,middle)
mergeSortHelper(lyst,copyBuffer,middle+1,high)
merge(lyst,copyBuffer,low,middle,high)
def merge(lyst,copyBuffer,low,middle,high):
i1 = low
i2 = middle + 1
for i in range(low,high+1):
if i1 > middle:
copyBuffer[i] = lyst[i2]
i2 += 1
elif i2 > high:
copyBuffer[i] = lyst[i1]
i1 += 1
elif lyst[i1] < lyst[i2]:
copyBuffer[i] = lyst[i1]
i1 += 1
else :
copyBuffer[i] = lyst[i2]
i2 += 1
for i in range(low,high+1):
lyst[i] = copyBuffer[i]
def main(size = 20,sort = mergeSort):
lyst = []
for count in range(size):
lyst.append(random.randint(1,size+1))
print(lyst)
sort(lyst)
print(lyst)
if __name__ == "__main__":
main()
以上内容为个人经验分享,希望能为大家提供参考,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













