Files
Python_CookBook_repo/1.数据结构与算法/4.最大N个和最小N个.py
2025-09-10 16:12:45 +08:00

34 lines
1.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import heapq
# heapq里有两个函数nlargest和nsmallest可以找最大N个和最小N个
# 参数接受一个列表和一个N
def max_n(search_list, n):
list_max_n = heapq.nlargest(n ,search_list)
return list_max_n
def min_n(search_list, n):
list_min_n = heapq.nsmallest(n, search_list)
return list_min_n
# 这两个函数都提供了一个key输入来实现在字典列表中的应用
def max_in_dictlist(search_list, n, key):
max_key_n = heapq.nlargest(n, search_list, key=lambda dic : dic[key])
return max_key_n
# 如果寻找最大N个和最小N个元素这个方法在N的规模不大的时候好用
# 当日在N=1的时候还是用max和min方法更快要是N巨大那就得排序了
# heapq事实上是一个堆方法将列表在底层序列化为一个最小堆
def heapq_func():
ori_list = [1,2,3,4,5]
heap = list(ori_list)
# 将列表进行堆排序
heapq.heapify(heap)
# 弹出堆顶元素
heapq.heappop(heap)
if __name__ == '__main__':
l = [1,2,3,4,5]
print(max_n(l, 3))