安装CAD/mindmanager出现Error 190
369 2023-04-03 04:58:35
heapq 的一些常用方法:
heapify(list)
将列表转换为小根堆的数据结构。
heappush(heap, x)
,将 x 加入堆中。
heappop(heap)
,从堆中弹出最小的元素。
heapreplace(heap, x)
,弹出最小的元素,并将 x 加入堆中。
heappushpop(heap, x)
,先把 x 加入堆中,再弹出最小的元素。
heapq.nlargest(n, heap)
,返回 heap 中前 n 个最大的元素。
heapq.nsmallest(n, heap)
,返回 heap 中前 n 个最小的元素。
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
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')))