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中pillow知识点学习

此系列意在记录于一些有趣的程序及对其的总结。 问题来源: https://github.com/Yixiaohan/show-me-the-code https://github.com...

python、PyTorch图像读取与numpy转换实例

Tensor转为numpy np.array(Tensor) numpy转换为Tensor torch.Tensor(numpy.darray) PIL.Image.Image转换成nu...

python原始套接字编程示例分享

python原始套接字编程示例分享

下面开始构造HTTP数据包, IP层和TCP层使用python的Impacket库,http内容自行填写。 复制代码 代码如下:#!/usr/bin/env python#-------...

python sort、sorted高级排序技巧

Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列。 1)排序基础 简单的升序排序是非常容易的。只需要...

Linux下为不同版本python安装第三方库

问题背景 目前的linux发行版上,有很多安装了两个版本的python。 我的机器上默认的版本为python 2.x。且在使用easy_install安装第三方库时,也默认安装到了2...