python实现获取序列中最小的几个元素

yipeiwu_com5年前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程序设计的学习有一定的借鉴价值。

相关文章

Python引用(import)文件夹下的py文件的方法

Python引用(import)文件夹下的py文件的方法

Python的import包含文件功能就跟PHP的include类似,但更确切的说应该更像是PHP中的require,因为Python里的import只要目标不存在就报错程序无法往下执行...

python中requests使用代理proxies方法介绍

学习网络爬虫难免遇到使用代理的情况,下面介绍一下如何使用requests设置代理: 如果需要使用代理,你可以通过为任意请求方法提供 proxies 参数来配置单个请求: impor...

Python批量修改文本文件内容的方法

Python批量替换文件内容,支持嵌套文件夹 import os path="./" for root,dirs,files in os.walk(path): for name...

python有证书的加密解密实现方法

本文实例讲述了python有证书的加密解密实现方法。分享给大家供大家参考。具体实现方法如下: 最近在做python的加解密工作,同时加完密的串能在php上能解出来,网上也找了一些靠谱的资...

django框架模板中定义变量(set variable in django template)的方法分析

本文实例讲述了django框架模板中定义变量的方法。分享给大家供大家参考,具体如下: 总有一些情况,你会想在django template中设置临时变量,但是django 对在模板中对临...