【Python练习cookbook】heapq高级应用

Python heapq库的用法介绍 阅读详情

heapq官方文档:https://docs.python.org/zh-cn/3/library/heapq.html#module-heapq

1.从集合中取出最大或最小N个元素

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

也支持其他参数支持更为复杂的数据结构

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'])

nlargest和nsmallest实现时先调用了heapify

 如果N与对象数量相差较大,则用nlargest和nsmaalest效率才高,否则先sorted再切片即可:

sorted(items)[:N] 
sorted(items)[-N:]

其实,当取出的N>size时,nlargest和nsmallest的实现就是用的sorted. 

                                                                                                                                                                                                       

补充heapq的其他常见函数说明:(引自:https://blog.youkuaiyun.com/brucewong0516/article/details/79042839)

数据结构堆(heap)是一种优先队列。使用优先队列能够以任意顺序增加对象,并且能在任意的时间(可能在增加对象的同时)找到(也可能移除)最小的元素,也就是说它比python的min方法更加有效率。

1、heappush(heap,n)数据堆入

In [1]: import heapq as hq
In [2]: import numpy as np
In [3]: data = np.arange(10)
#将生成的数据随机打乱顺序
In [4]: np.random.shuffle(data)
In [5]: data
Out[5]: array([5, 8, 6, 3, 4, 7, 0, 1, 2, 9])
#定义heap列表
In [6]: heap = []
#使用heapq库的heappush函数将数据堆入
In [7]: for i in data:
   ...:     hq.heappush(heap,i)
   ...:
In [8]: heap
Out[8]: [0, 1, 3, 2, 5, 7, 6, 8, 4, 9]

In [9]: hq.heappush(heap,0.5)
In [10]: heap
Out[10]: [0, 0.5, 3, 2, 1, 7, 6, 8, 4, 9, 5]

2、heappop(heap)将数组堆中的最小元素弹出

In [11]: hq.heappop(heap)
Out[11]: 0

In [12]: hq.heappop(heap)
Out[12]: 0.5

3、heapify(heap) 将heap属性强制应用到任意一个列表

heapify 函数将使用任意列表作为参数,并且尽可能少的移位操作,,将其转化为合法的堆。如果没有建立堆,那么在使用heappush、heappop、heapreplace前应该使用该函数。

In [13]: heap = [5,8,0,3,6,7,9,1,4,2]

In [14]: hq.heapify(heap)

In [15]: heap
Out[15]: [0, 1, 5, 3, 2, 7, 9, 8, 4, 6]

heap = [5,8,0,3,6,7,9,1,4,2]
hq.heappop(heap)
Out[70]: 5
heap = [5,8,0,3,6,7,9,1,4,2]
hq.heapify(heap)
hq.heappop(heap)
Out[73]: 0
heap = [5,8,0,3,6,7,9,1,4,2]
hq.heapreplace(heap,10)
Out[75]: 5
heap = [5,8,0,3,6,7,9,1,4,2]
hq.heapify(heap)
hq.heapreplace(heap,10)
Out[78]: 0



4、heapreplace(heap,n)弹出最小的元素被n替代

In [17]: hq.heapreplace(heap,0.5)
Out[17]: 0

In [18]: heap
Out[18]: [0.5, 1, 5, 3, 2, 7, 9, 8, 4, 6]

5、nlargest(n,iter)、nsmallest(n,iter)
heapq中剩下的两个函数nlargest(n.iter)和nsmallest(n.iter)分别用来寻找任何可迭代的对象iter中第n大或者第n小的元素。可以通过使用排序(sorted函数)和分片进行完成。

#返回第一个最大的数
In [19]: hq.nlargest(1,heap)
Out[19]: [9]
#返回第一个最小的数
In [20]: hq.nsmallest(1,heap)
Out[20]: [0.5]
————————————————
版权声明:本文为优快云博主「brucewong0516」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/brucewong0516/article/details/79042839

                                                                                                                                                                                                       

2.实现一个队列,该队列按给定的优先级对元素进行排序,并使pop操作始终返回每个优先级最高的元素

import heapq

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]

heapq.heappush(queue,item)会按item1

其中,优先级前加负号可让堆有优先级从高到低排序。index用于处理优先级一样的元素。

index的另一个作用是避免优先级和index一样时(因为index不可能相同),比较item:

>>> a = (1, Item('foo'))
>>> b = (5, Item('bar'))
>>> a < b
True
>>> c = (1, Item('grok'))
>>> a < c
Traceback (most recent call last):
File "", line 1, in
TypeError: unorderable types: Item() < Item()

因为我们并未定义Item的比较操作,所以会报如上错误

应用实例:

>>> class Item:
...     def __init__(self, name):
...        self.name = name
...    def __repr__(self):
...         return 'Item({!r})'.format(self.name)
...
>>> q = PriorityQueue()
>>> q.push(Item('foo'), 1)
>>> q.push(Item('bar'), 5)
>>> q.push(Item('spam'), 4)
>>> q.push(Item('grok'), 1)
>>> q.pop()
Item('bar')
>>> q.pop()
Item('spam')
>>> q.pop()
Item('foo')
>>> q.pop()
Item('grok')

从零开始:面板数据熵值法的Stata实现与常见陷阱解析 本文详细介绍了面板数据熵值法在Stata中的实现步骤与常见陷阱解析。通过熵值法客观赋权特性,科学构建综合指数,特别适合处理多维面板数据。文章涵盖数据预处理、标准化方法选择、Stata代码实现及结果可视化,并针对常见问题提供实用解决方案,助力研究者避免分析误区。 阅读详情

相关推荐

一篇讲透:豆包、元宝、DeepSeek、Kimi、WorkBuddy,职场里到底怎么分工

这篇文章深入分析了当前主流AI工具(WorkBuddy、豆包、腾讯元宝、DeepSeek、Kimi)的特点和使用场景,帮助读者根据不同工作需求选择合适的AI助手。核心观点包括: AI工具各有所长:豆包适合快速创作初稿,元宝擅长信息检索整理,DeepSeek强于逻辑分析,Kimi专精文本处理,WorkBuddy则更适合任务推进和成果交付。 使用前需明确需求:是要创意发散、信息整理,还是任务执行?不同阶段应选用不同工具组合。 提供了6个具体职场场景的解决方案,包括文章创作、课程设计、会议纪要等,并给出详细的操作

weixin_39284145的博客 1万+

Python 基础 (标准库):heapq (堆)

Python 基础(标准库):堆 heap

AbigailQin 的博客 1万+

用Multisim和AD2复刻经典:手把手教你搭建μA741三角波-方波发生器(附完整避坑指南)

本文详细介绍了如何使用Multisim和AD2搭建基于μA741运算放大器的三角波-方波发生器,包括电路原理、Multisim仿真流程、AD2硬件搭建及调试技巧。通过对比理论计算、仿真和实测数据,深入分析器件非理想特性的影响,并提供16个典型问题的解决方案,帮助读者掌握波形发生器的设计原理和工程调试经验。

weixin_28744423的博客 284

python3中的heapq模块(堆排序)使用

heapq-堆排序算法:heapq实现了一个适合与Python的列表一起使用的最小堆排序算法。堆就是用数组表示的二叉树,分为大根堆和小根堆,大根堆为堆顶元素最大的堆,小根堆为堆顶元素最小的堆。

flyingluohaipeng的博客 9242

VSCode配置C/C++语言环境(小白专用保姆教程)(超细)

VSCode配置C/C++语言环境(小白专用保姆教程)(超细)

ITQWQ的博客 8229

Androiud安卓链接sqllite的代码使用案例

【代码】Androiud安卓链接sqllite的代码使用案例。

laterstage的博客 1328

python中的heapq库

heapq库

苏钟白的博客 6040

时序分析28 - 时序预测 格兰杰因果关系(中) python实践1

时序分析28 - 时序预测 - 格兰杰因果关系(中) Python 实践 1 上一篇文章我们介绍了格兰杰因果关系的基本概念、背景以及相关统计检验法。本篇文章我们使用Python编程实践一下。 实践1:股票价格数据之间的格兰杰因果关系 问题:苹果公司今天的股价是否可以用来预测明天的特斯拉的股价? 数据:来自雅虎财经 import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd 读入数据

weixin_43171270的博客 8836

Python的heapq模块

模块是Python标准库中的一个模块,提供了对堆(heap)数据结构的支持。

sinat_31608641的博客 2636

东北大学计算机预推免(双非友好)

东北大学,个人觉得在985里面对双非比较友好,而且学校的计算机专业实力也比较强,上岸难度不算很大,可以重点关注一下。学校复试审核的时间比较早,拿到复试资格之后,一定要留意报名系统首页中计算机学院的信息,学校也会在全国各地不同时间安排面试,可以根据自己的情况选择一个合适的时间前去面试,并且有对应面试场次的QQ群,信息会在群里面发布。面试成绩会在预推免系统中直接公布,但是是否拟录取不会公布,需要考生自行判断,今年计算机学院录取线定在了86分左右,最终递补下来,好像录取到了84分左右。

D1379951481的博客 3120

innovus:ccopt_design流程

我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?spec文件可以只创建一次,无需多次创建。2)virtual balance阶段。3)Full Balancing阶段。4)Clock Routing阶段。1)clustering阶段。

m0_61544122的博客 2477

Python Cookbook读书笔记

Python Cookbook读书笔记

pku_langzi的博客 1646

Python 爬虫实战:科研数据库学术论文数据抓取

在科研工作中,学术论文是获取前沿知识和研究方法的重要资源。然而,手动从科研数据库中查找和整理论文信息往往耗时费力。幸运的是,Python 爬虫技术可以自动化这一过程,帮助我们高效地抓取和管理学术论文数据。本文将详细介绍如何使用 Python 爬虫技术抓取科研数据库中的学术论文数据,并进行全字段提取和文献管理,助力科研工作。

u014481728的博客 945

Python 标准库heapq,堆数据结构操作详解

heapq 是 Python 标准库中的一个基于堆的优先队列实现。它提供了一些函数来实现对列表中的元素进行加入、弹出、替换等操作,同时也支持对列表中的元素进行建堆、堆排序等高级功能。本文将详细介绍 heapq 的使用方法和内部实现原理。

DataShare 924

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

python-cookbook

PYTHON-COOKBOOK 文章目录PYTHON-COOKBOOK一:数据结构和算法1、Heapq取出最大或最小的几个元素优先级队列2、字典多值字典字典排序字典列表排序字典共同点和不同点3、collections保留最后几个元素频率统计命名元组字典(映射)联合查找4、其他解压赋值去重且保持顺序切片分组 一:数据结构和算法 三个基本的写法: 列表生成式 字典生成式 迭代器生成式 1、H...

(-_-) 737

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

python cookbook内容提炼-第一章数据结构和算法

第一章的内容很实用,博主做了一些内容上的提炼,把一些最重要的知识点写在了下面。 下面内容中,字体小的内容实在开发中不常用的,其他的都是比较重要的内容,感兴趣,可以掌握一下。

weixin_43327597的博客 1327

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

python cookbook 1.4 找到最大或者最小的N个元素 heapq

#1.4找到最大或最小的N个元素,堆 #heapq模块中两个函数 nlargest()和nsmallest() import heapq nums = [5,12,6,2,7,3,-1,-6,66] print(heapq.nlargest(3,nums)) #最大的3个元素 print(heapq.nsmallest(3,nums)) #最小的3个元素 #这两个函数都可以接受参...

别说话写代码的博客 231

python Cookbook

import sys import numpy as np # 可迭代对象中分解元素 *表达式 grades=[1,2,2,2,2,2,8] first,*middle,last=grades avgs= np.mean(middle) *trailing,current =[10,8,7,1,9,5,10,3] # print(trailing) # print(curren...

weixin_30507269的博客 123

python cookbook 4.15 顺序迭代合并后的排序迭代对象 heapq.merge()

#有一系列排序序列,想将他们合并后得到一个排序序列并在上面迭代遍历,heapq.merge()函数可以帮你解决这个问题 import heapq a=[1,3,5,7] b=[2,4,6,8] for x in heapq.merge(a,b): print(x) #heapq.merge()可迭代特性意味着它不会立马读取所有序列。意味着你可以在非常长的序列中使用它,而不会有太大...

别说话写代码的博客 310

python cookbook pdf java1234_Python Cookbook 学习笔记(一):数据结构和算法

写在前面人生苦短,我用Python。Python是一门简洁又强大的编程语言。比起C++/Java等语言,Python拥有简单易懂的语法,极易上手,专注于解决问题,而非语言本身。同时,Python拥有丰富的库,为各种工作提供支持,如网页开发(Django)、科学计算(Numpy)、软件开发(SCons)等[1]。虽然Python运行效率比不上C++/Java,但开发者会使用Python进行快速开发原...

weixin_39664962的博客 190

python cookbook是什么_python cookbook

一 .数据结构python collections包中deque :固定长度队列,(例如固定长度的cache什么的)defaultdict:如果每个键值不存在,默认返回值orderdict:有顺序的字典,按照插入的顺序,该结构内部维护了一个根据键插入顺序排序的双向链表。counter: 频率计算器,将一个列表冲出现的重复元素,组合成为{元素:频率}字典表,以及一些函数。nametuple:命名记录...

weixin_39590868的博客 457

Python CookBook(self report)

Python CookBook 中文版:https://python3-cookbook.readthedocs.io/zh_CN/latest/copyright.html 英文版:https://d.cxcore.net/Python/Python_Cookbook_3rd_Edition.pdf Data Structures and Algorithms start expres...

PresleyR的博客 287

Python Cookbook 学习笔记 第一章Data Structures and Algorithms

今天学习完了一部分Cookbook书上的内容,做一个笔记。 一、问题:如何将一个N个元素的元组或者序列拆解成为N个变量。 解决:对于任何 iterable的对象,例如元组、列表、文件、迭代器、生成器都可以采用简单赋值操作来完成这个任务。唯一的要求是要求变量的个数与序列中的元素个数是匹配的。例如: >>> data = [ 'ACME', 50, 91.1, (2012, 12,

xiaoka1993的博客 1023

【Python练习cookbook】字典dictionary高级操作

1.字典键-值对中,值元素的便捷创建增减 主要是利用collections 中的defaultdict 普通复杂过程: pairs = [('a', 1), ('a', 2),('b', 2)] d = {} for key, value in pairs: if key not in d: d[key] = [] #指定值为list类型 d[key].ap...

Code_LT的博客 504

(转)Python cookbook学习总结

原创 Python cookbook学习总结 ...

qq_41978139的博客 204

python3 cookbook_Python3 CookBook |

以下测试代码全部基于 Python31、查找最大或最小的 N 个元素工作中有时会遇到这样的需求,取出数据中前面 10% 的值,或者最后 10% 的值。我们可以先对这个列表进行排序,然后再进行切片操作,很轻松的解决这个问题。但是,有没有更好的方法呢?heapq 模块有两个函数 nlargest() 和 nsmallest() 可以完美解决这个问题。In [50]: import heapqIn [5...

weixin_39686192的博客 206
上一篇: MBA备考初探
下一篇: 【Python练习cookbook】字典dictionary高级操作
Code_LT
博客等级 码龄10年 307粉丝 182原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值