熱線電話:13121318867

登錄
首頁精彩閱讀python實現獲取序列中最小的幾個元素
python實現獲取序列中最小的幾個元素
2018-06-27
收藏

python實現獲取序列中最小的幾個元素

本文實例講述了python實現獲取序列中最小的幾個元素。分享給大家供大家參考。

具體方法如下:   
import heapq
import random
def issorted(data):
 data = list(data)
 heapq.heapify(data)
 while data:
  yield heapq.heappop(data)
   
alist = [x for x in range(10)]
random.shuffle(alist)
print 'the origin list is',alist
print 'the min in the list is'
for x in issorted(alist):
 print x,
程序運行結果如下:   
the origin list is [2, 3, 4, 9, 8, 5, 1, 6, 0, 7]
the min in the list is
0 1 2 3 4 5 6 7 8 9
使用了heapq模塊和random模塊.heapq二叉樹,常用來處理優先級序列問題。
此外還有一個更為簡單的方法:
print heapq.nsmallest(3,alist) #打印出alist列表中最小的三個元素最小,如果是字母就是按字母序比較
感興趣的朋友可以測試運行本文實例,相信本文所述對大家Python程序設計的學習有一定的借鑒價值

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢