python heapq堆排序精讲

python heapq堆排序精讲

python heapq相关操作

heapq 的一些常用方法

  1. heapify(list)将列表转换为小根堆的数据结构。

  2. heappush(heap, x),将 x 加入堆中。

  3. heappop(heap),从堆中弹出最小的元素。

  4. heapreplace(heap, x),弹出最小的元素,并将 x 加入堆中。

  5. heappushpop(heap, x),先把 x 加入堆中,再弹出最小的元素。

  6. heapq.nlargest(n, heap),返回 heap 中前 n 个最大的元素。

  7. heapq.nsmallest(n, heap),返回 heap 中前 n 个最小的元素。

如何自定义堆排序?

重写__lt__方法

import heapqa = range(10)class Node:    def __init__(self, v):        self.v = v    def __lt__(self, other):        # 自定义lt便可实现大顶堆        return self.v > other.vh = []for i in a:    heapq.heappush(h, Node(i))ans = heapq.nsmallest(len(h), h)for i in ans:    print(i.v)a = [(1, 'asd', 2), (2, 'asd', 2), (1, 'asd', 3), (5, 'asd', 3), (1, 'fd', 3)]# 对于a想要按照第一个数从大到小,第二个字符串从大到小,第三个数字从小到大排序class Node:    def __init__(self, v):        self.a, self.b, self.c = v[0], v[1], v[2]    def __lt__(self, other):        if self.a != other.a:            return self.a > other.a        if self.b != other.b:            return self.b > other.b        return self.c < other.ch = []for i in a:    heapq.heappush(h,Node(i))ans = heapq.nsmallest(len(h),h)for i in ans:    print(i.a,i.b,i.c)# 5 asd 3# 2 asd 2# 1 fd 3# 1 asd 2# 1 asd 3

利用itemgetter

from operator import itemgetterimport heapqlist1 = [1, 6, 4, 3, 9, 5]list2 = ['12', 'a6', '4', 'c34', 'b9', '5']list3 = [    {'name': 'jim', 'age': 23, 'price': 500},    {'name': 'mase', 'age': 23, 'price': 600},    {'name': 'tom', 'age': 25, 'price': 2000},    {'name': 'alice', 'age': 22, 'price': 300},    {'name': 'rose', 'age': 21, 'price': 2400},]print(heapq.nlargest(len(list1), list1))print(heapq.nlargest(len(list2), list2))print(heapq.nlargest(len(list3), list3, key=itemgetter('age', 'price')))print(heapq.nsmallest(len(list1), list1))print(heapq.nsmallest(len(list2), list2))print(heapq.nsmallest(len(list3), list3, key=itemgetter('age', 'price')))
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部