本文實例講述了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程序設計的學習有一定的借鑒價值。
本文標題: python實現獲取序列中最小的幾個元素
本文地址: http://www.cppcns.com/jiaoben/python/114221.html