Python3实现自定义比较排序/运算符
作者:as1171799253 发布时间:2023-04-15 23:32:25
标签: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 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)]
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=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()
来源:https://blog.csdn.net/as1171799253/article/details/83685615


猜你喜欢
- 前言本文主要介绍了关于python中os和sys模块区别与常用方法的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧
- 前言 好长时间没摸数据库了,周末在家写了个报表的存储过程,一时间对使用存储过程实
- 在二维矩阵间的运算:class torch.nn.Conv2d(in_channels, out_channels, kernel_size
- 1.数据的容量:1-3年内会大概多少条数据,每条数据大概多少字节; 2.数据项:是否有大字段,那些字段的值是否经常被更新; 3.数据查询SQ
- 1、PandasPython Data Analysis Library 或 pandas 是基于NumPy 的一种工具,相当于这是Pyth
- 最近公司项目加了个页面,其中要求是这样的,点击对应列表,展开和收起,其实就是显示和隐藏内容部分;说来惭愧,我花了半天时间才搞出来(自黑一下~
- tensorflow下设置使用某一块GPU(从0开始编号):import osos.environ["CUDA_DEVICE_OR
- 1.概述随着人工智能技术的不断发展,越来越多的AI产品被应用到各个领域,其中最具代表性的莫过于人工智能语言模型。语言模型是一种可以通过学习大
- 模块的作用是:允许从任何文件里得到任何一行或几行,并且使用缓存进行优化。有几个API接口linecache.getlines(filenam
- 1.先用 for 循环取for item in l: if isinstance(item ,list): &nb
- 工作中最常见的配置文件有四种:普通key=value的配置文件、Json格式的配置文件、HTML格式的配置文件以及YMAML配置文件。这其中
- python 读取语音文件时,常用的无非以下三种方式,但是在我们数据量变的很大是,不同的读取方式之间的性能差异就会被进一步放大,于是本文着重
- 1、获取文件的创建、修改、访问时间# -*- encoding=utf-8 -*-import osimport timedef get_f
- 目录一、MySQL触发器创建:1、MySQL触发器的创建语法:2、MySQL创建语法中的关键词解释:3、触发执行语句内容(trigger_b
- 数据结构&Series:'''series {索引 + 数据} 形式索引是自动生成的''
- 1、例子:拟合一种函数Func,此处为一个指数函数。出处:SciPy v1.1.0 Reference Guide#Headerimport
- Oracle的out参数实例详解一 概念1、一般来讲,存储过程和存储函数的区别在于存储函数可以有一个返回值;而存储过程没有返回值。2、过程和
- —— 八数码难题 ——1.题目描述八数码问题也称为九宫问题。在3×3的棋盘,摆有八个棋子,每个棋子上标有1至8的某一数字,不同棋子上标的数字
- 废话不多说,直接上代码Python2.7#!/usr/bin/env python2.7# -*- coding=utf-8 -*-impo
- 函数 &n