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

yipeiwu_com6年前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实现一个大数据搜索引擎

浅谈用Python实现一个大数据搜索引擎

搜索是大数据领域里常见的需求。Splunk和ELK分别是该领域在非开源和开源领域里的领导者。本文利用很少的Python代码实现了一个基本的数据搜索功能,试图让大家理解大数据搜索的基本原理...

python 读取.csv文件数据到数组(矩阵)的实例讲解

利用numpy库 (缺点:有缺失值就无法读取) 读: import numpy my_matrix = numpy.loadtxt(open("1.csv","rb"),delim...

Python中的getopt函数使用详解

函数原型: getopt.getopt(args, shortopts, longopts=[]) 参数解释:     args:args...

Python获取时间范围内日期列表和周列表的函数

Python获取时间范围内日期列表和周列表的函数

Python获取时间范围内日期列表和周列表的函数 1、获取日期列表 # -*- coding=utf-8 -*- import datetime def dateRange(beg...

详解Python循环作用域与闭包

前言 首先来看一段代码 x_list = [i for i in range(30)] y_list = [i for i in range(10, 20)] for y in y...