国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python cookbook(數據結構與算法)找到最大或最小的N個元素實現方

2020-02-22 23:15:31
字體:
來源:轉載
供稿:網友

本文實例講述了python找到最大或最小的N個元素實現方法。分享給大家供大家參考,具體如下:

問題:想在某個集合中找出最大或最小的N個元素

解決方案:heapq模塊中的nlargest()nsmallest()兩個函數正是我們需要的。

>>> import heapq>>> nums=[1,8,2,23,7,-4,18,23,42,37,2]>>> print(heapq.nlargest(3,nums))[42, 37, 23]>>> print(heapq.nsmallest(3,nums))[-4, 1, 2]>>>

這兩個函數接受一個參數key,允許其工作在更復雜的數據結構之上:

# example.py## Example of using heapq to find the N smallest or largest itemsimport heapqportfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65}]cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])print(cheap)print(expensive)
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>>[{'name': 'YHOO', 'price': 16.35, 'shares': 45}, {'name': 'FB', 'price': 21.09, 'shares': 200}, {'name': 'HPQ', 'price': 31.75, 'shares': 35}][{'name': 'AAPL', 'price': 543.22, 'shares': 50}, {'name': 'ACME', 'price': 115.65, 'shares': 75}, {'name': 'IBM', 'price': 91.1, 'shares': 100}]>>>

如果正在尋找的最大或最小的N個元素,且相比于集合中元素的數量,N很小時,下面的函數性能更好。

這些函數首先會在底層將數據轉化為列表,且元素會以堆的順序排列。

>>> import heapq>>> nums=[1,8,2,23,7,-4,18,23,42,37,2]>>> heap=list(nums)>>> heap[1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]>>> heapq.heapify(heap) #heapify()參數必須是list,此函數將list變成堆,實時操作。從而能夠在任何情況下使用堆的函數。>>> heap[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]>>> heapq.heappop(heap)#如下是為了找到第3小的元素-4>>> heapq.heappop(heap)1>>> heapq.heappop(heap)2>>>

堆(heap)最重要的特性就是heap[0]總是最小的元素。可通過heapq.heappop()輕松找到最小值,這個操作的復雜度為O(logN),N代表堆得大小。

總結:

1、當要找的元素數量相對較小時,函數nlargest()nsmallest()才最適用。
2、若只是想找到最小和最大值(N=1)時,使用min()和max()會更快。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 攀枝花市| 北川| 调兵山市| 娱乐| 集安市| 同仁县| 巴林左旗| 洞口县| 山阴县| 黔江区| 泸定县| 汾西县| 福建省| 普安县| 瑞金市| 栾川县| 溆浦县| 大埔县| 安龙县| 崇礼县| 永和县| 乌鲁木齐县| 屏东县| 东宁县| 宁南县| 子洲县| 海盐县| 民权县| 井研县| 岱山县| 徐闻县| 邯郸市| 易门县| 贵阳市| 富民县| 安丘市| 五常市| 铁岭县| 玉林市| 大石桥市| 贵定县|