Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement self-defined comparison sorting by Python3

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to achieve custom comparison sorting in Python3". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Custom comparison sort / operator

Python3 has a lot of changes compared to Python2.

In Python2, you can directly write a cmp function as an argument to sort to customize the sort, but Python3 cancels it.

Here is a summary of the two ways to write Python3's custom sorting, welcome to add.

We use the points in the two-dimensional space as the data structure to be sorted, and we want to be able to compare x before comparing 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 function

The first method is in the form of rewriting cmp or lambda expressions, which is very similar to Python2

Note that this method cannot be sorted successfully with sorted

Just with the help of functools

Import functoolsdef cmp (a, b): return a.x-b.x if a.x! = b.x else a.y-b.y # x y are all in the order from small to big if _ _ name__ = ='_ _ main__': test_list = [Pos (5,1), 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)) # this method can not successfully sort the print (test_list) # output [(2,4), (2,5), (5,1)] 2. Override class methods

The _ _ cmp__ method can be directly overridden in Python2 to achieve comparison, but it has been cancelled in Python3.

Each comparison operator needs to be subdivided in Python3.

_ lt__: _ ge__: > = _ eq__: = = _ le__: 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 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 minute sizebuffer 1)) print (lyst) sort (lyst) print (lyst) if _ name__ = = "_ _ main__": main () "how Python3 implements custom comparison sorting" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report