欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)獲取序列中最小的幾個元素

 更新時間:2014年09月25日 16:05:44   投稿:shichen2014  
這篇文章主要介紹了python實(shí)現(xiàn)獲取序列中最小的幾個元素,是非常實(shí)用的技巧,需要的朋友可以參考下

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

具體方法如下:

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,

程序運(yùn)行結(jié)果如下:

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二叉樹,常用來處理優(yōu)先級序列問題。

此外還有一個更為簡單的方法:

print heapq.nsmallest(3,alist) #打印出alist列表中最小的三個元素最小,如果是字母就是按字母序比較

感興趣的朋友可以測試運(yùn)行本文實(shí)例,相信本文所述對大家Python程序設(shè)計的學(xué)習(xí)有一定的借鑒價值。

相關(guān)文章

最新評論