Python3怎么实现自定义比较排序
发表于:2025-02-09 作者:千家信息网编辑
千家信息网最后更新 2025年02月09日,本篇内容介绍了"Python3怎么实现自定义比较排序"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!自
千家信息网最后更新 2025年02月09日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__
1.cmp函数
第一种方法我们还是以重写cmp或lambda表达式的形式,和Python2很类似
注意,此方法用sorted是不能成功排序的
只是要借助functools
import functoolsdef 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)]
2.重写类方法
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=gbkimport randomfrom array import arraydef 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()
"Python3怎么实现自定义比较排序"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!
排序
复杂
方法
输出
情况
成功
内容
函数
更多
此方法
知识
运算符
a.x
b.x
运算
实用
从小到大
学有所成
接下来
从小
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
传世奔月服务器
合肥软件开发国企有那些
数据库operation
服务器发布管理工具
公安网络安全多少工资
维修小程序用什么数据库好
戴尔服务器清除raid缓存
网络安全指尖上的陷阱
3d定制捏脸数据库
观看网络安全法纪警示教育片发言
最基本的软件开发
软件开发的项目建议书
常见服务器默认管理口地址
云南云科网络技术有限公司
联合作战网络安全防护
华为网络技术工程师辛不辛苦
工业互联网和网宿科技
深圳软件开发咨询
千方科技互联网
胡蓉 网络安全
河南融顺网络技术有线公司
宁波专业软件开发管理
数据库彪设计原则
国家网络安全证书照片
规范人员管理 网络安全
我们未来的网络安全
上海支付软件开发的公司排名
天津 软件开发 项目经理
常见的网络安全服务器
百度软件开发工程师照片