用headp找到最大最小的N个值

import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
[42, 37, 23]
[-4, 1, 2]

数据结构复杂时

可以用key这个参数,传入一个lambda表达式

portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) print(cheap)
print(expensive)
[{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}]
[{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}, {'name': 'IBM', 'shares': 100, 'price': 91.1}]
## 当N的大小和元素差不多时,可以直接用sorted
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
sorted(nums,reverse=False)[-3:]
# 默认从小到大,改成True从小到大
[23, 37, 42]

也可以让一个列表堆化

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
heapq.heapify(nums)
nums
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
print(heapq.heappop(nums))
print(heapq.heappop(nums))
print(heapq.heappop(nums))
# 相对较大
-4
1
2

使用headp实现优先队列

## 优先级为负先弹出高的
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0 def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1 def pop(self):
return heapq.heappop(self._queue)[-1] # Example use
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)#tostring q = PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('bar'), 5)
q.push(Item('spam'), 4)
q.push(Item('grok'), 1) print("Should be bar:", q.pop())
print("Should be spam:", q.pop())
print("Should be foo:", q.pop())
print("Should be grok:", q.pop())
Should be bar: Item('bar')
Should be spam: Item('spam')
Should be foo: Item('foo')
Should be grok: Item('grok')

Python数据结构 - 利用headp模块寻找最大N个元素并实现优先队列的更多相关文章

  1. python:利用xlrd模块操作excel

    在自动化测试过程中,对测试数据的管理和维护是一个不可忽视的点.一般来说,如果测试用例数据不是太多的话,使用excel管理测试数据是个相对来说不错的选择. 这篇博客,介绍下如何利用python的xlrd ...

  2. python:利用configparser模块读写配置文件

    在自动化测试过程中,为了提高脚本的可读性和降低维护成本,将一些通用信息写入配置文件,将重复使用的方法写成公共模块进行封装,使用时候直接调用即可. 这篇博客,介绍下python中利用configpars ...

  3. python:利用logbook模块管理日志

    日志管理作为软件项目的通用部分,无论是开发还是自动化测试过程中,都显得尤为重要. 最初是打算利用python的logging模块来管理日志的,后来看了些github及其他人的自动化框架设计,做了个比对 ...

  4. python:利用pymssql模块操作SQL server数据库

    python默认的数据库是 SQLlite,不过它对MySql以及SQL server的支持也可以.这篇博客,介绍下如何在Windows下安装pymssql库并进行连接使用... 环境:Windows ...

  5. python:利用smtplib模块发送邮件

    自动化测试中,测试报告一般都需要发送给相关的人员,比较有效的一个方法是每次执行完测试用例后,将测试报告(HTML.截图.附件)通过邮件方式发送. 参考代码:send_mail.py 一.python对 ...

  6. hdf 5文件格式及python中利用h5py模块读写h5文件

    h5文件格式,HDF 的版本 5(HDF 版本 5不与 HDF 版本 4 及早期版本兼容).HDF是什么呢?就是Hierarchical Data Format,可以存储不同类型的图像和数码数据的文件 ...

  7. python:利用smtplib模块发送邮件详解

    自动化测试中,测试报告一般都需要发送给相关的人员,比较有效的一个方法是每次执行完测试用例后,将测试报告(HTML.截图.附件)通过邮件方式发送. 首先我们要做: 进入163邮箱,点击设置中的pop3/ ...

  8. python之~利用PIL模块在图片上写写画画

    借鉴了教程: http://yxnt.github.io/2016/05/15/Pillow-Python3.5/ 完成作业如下: 后来学着写给自己的图片加了水印. from PIL import I ...

  9. 利用python自动生成verilog模块例化模板

    一.前言 初入职场,一直忙着熟悉工作,就没什么时间更新博客.今天受“利奇马”的影响,只好宅在家中,写写技术文章.芯片设计规模日益庞大,编写脚本成了芯片开发人员必要的软技能.模块端口动不动就几十上百个, ...

随机推荐

  1. 【Java并发】线程的顺序执行

    /** * 问题:有线程a.b.c,如何让它们顺序执行? * 方式一:可用Join()方法实现 * 方式二:可用newSingleThreadExecutor() * Created by Smile ...

  2. 选择排序&冒泡排序&折半查找

    //选择排序 void test2(int a[],int len){ //每次找出一个最小值,最小值依次与原数组交换位置,通过下标来完成交换,最小值下标每次都在变,变量存储 //    假如第一个是 ...

  3. JMeter使用代理进行录制

    参考: http://www.cnblogs.com/zhuque/archive/2012/11/13/2767747.html JMeter支持第三方(Badboy)录制和代理录制,Badboy录 ...

  4. hdu2222 Keywords Search (AC自动机板子

    https://vjudge.net/problem/HDU-2222 题意:给几个模式串和一个文本串,问文本串中包含几个模式串. 思路:贴个板子不解释. #include<cstdio> ...

  5. codeforce617E-XOR and Favorite Number莫队+异或前缀和

    传送门:http://codeforces.com/contest/617/problem/E 参考:https://blog.csdn.net/keyboarderqq/article/detail ...

  6. CodeForces 592D Super M DP

    Super M 题解: 定义 dp[u][0] 为遍历完u中的所有节点, 但不回到u点的路径花费值. 定义 dp[u][1] 为遍历完u中的所有节点, 且要回到u点的路径花费值. 转移方程. dp[u ...

  7. 迷宫问题 POJ - 3984 [kuangbin带你飞]专题一 简单搜索

    定义一个二维数组: int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, ...

  8. 题解 UVA12716 GCD等于XOR GCD XOR

    规律题,打表找规律即可发现 a xor b >= a - b >= gcd(a, b), 如果 a xor b = gcd(a, b) = c 则 c = a - b 枚举倍数c和a判断b ...

  9. 【LeetCode】33-搜索旋转排序数组

    题目描述 假设按照升序排序的数组在预先未知的某个点上进行了旋转. ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] ). 搜索一个给定的目标值,如果数组中存在这 ...

  10. Factory Method工厂方法模式

    定义一个用于创建对象的接口,让子类决定将哪一个类实例化.Factory Method使一个类的实例化延迟到其子类,属于创建型模式 在此模式中,工厂父类负责定义创建产品对象的公共接口,而工厂子类负责生产 ...