首页 > 其他分享 >取列表或字典最大/最小的前几个

取列表或字典最大/最小的前几个

时间:2023-06-18 10:01:56浏览次数:27  
标签:heapq nsmallest 最小 列表 dict topNum print nlargest 字典

import heapq

a_list = [3, 4, 2, 5, 1, 6]
c_dict = {'A': 3, 'B': 4, 'C': 5}
topNum = 2

print(heapq.nlargest(topNum, a_list))
print(heapq.nlargest(topNum, c_dict))
print(heapq.nlargest(topNum, c_dict.keys()))
print(heapq.nlargest(topNum, c_dict.values()))
print('=' * 15)
print(heapq.nsmallest(topNum, a_list))
print(heapq.nsmallest(topNum, c_dict))
print(heapq.nsmallest(topNum, c_dict.keys()))
print(heapq.nsmallest(topNum, c_dict.values()))

结果

[6, 5]
['C', 'B']
['C', 'B']
[5, 4]
===============
[1, 2]
['A', 'B']
['A', 'B']
[3, 4]

 

标签:heapq,nsmallest,最小,列表,dict,topNum,print,nlargest,字典
From: https://www.cnblogs.com/daizichuan/p/17488727.html

相关文章

  • 关于最小生成树
    关于最小生成树目录概述性质Prim算法实现例P1194买礼物Kruskal算法实现思想例P4047部落划分Part1概述一个连通图的生成树是一个极小的连通子图,它包含图中全部的n个顶点,但只有构成一棵树的n-1条边。我们定义无向连通图的最小生成树(MinimumSpannin......
  • [ Shell ] 在 Bash 中如何使用“字典”
    https://www.cnblogs.com/yeungchie/定义declare-Adict赋值批量赋值dict=([a]=1[b]=2[c]=3)追加赋值dict[lib]=topdict[cell]=XX1234dict[view]=layout取值取值方式与数组一样。echo"${dict[a]}"#1echo"${dict[cell]}"#XX1234打印所有key和value......
  • 写一个删除列表中重复元素的函数,要求去重后元素相对位置保持不变
    1#无集合setlist_=['a','a','b','b','c','c']list_new=[]foriinlist_:ifinotinlist_new:list_new.append(i)list_newdeffun_1(list_=['a','a','b'......
  • 列表生成式
    '''列表生成式即ListComprehensions'''#https://www.liaoxuefeng.com/wiki/1016959663602400/1017317609699776list(range(1,11))#生成range序列不能用[][x+0forxinrange(1,11)]#遍历对象A中的每个元素a对之进行处理将结果a'保存到列表中[x+0forxinrange......
  • Python数据类型-字典与集合
    """题目1:下面关于字典的定义正确的是:CA.d={1,}B.d={1,2:3,4}C.d={'name':'xinlan','age':18}D.d={[1,2]:[3,4],'age':18}"""#题目2:请创建一个字典用来表示你自己的个人信息。有哪些key由你自己来决定。my_info={'name':&......
  • Python元组(tuple)和字典(dict)的合并使用
    Python包含6种数据类型,其中Number(数字)、String(字符串)、Tuple(元组)、 List(列表)、Dictionary(字典)、Set(集合);1.回顾Tuple(元组)的常用方法:Tuple的创建:tuple()方法创建,或者小括号的方式,有时也直接省略小括号a=tuple(range(10))b=tuple('hkd')c=tuple([1,2,3])PS:tuple()......
  • Python数据类型-列表与元组
    #题目1:删除如下列表中的"矮穷丑",写出2种或以上方法:#info=["yuze",18,"男","矮穷丑",["高","富","帅"],True,None,"狼的眼睛是啥样的"]info=["yuze",18,"男","矮穷丑",["......
  • 在Python中根据字典值寻找键
    问题描述  在处理VOC数据集时,创建的字典如下所示label_map={0:'background',1:'aeroplane',2:'bicycle',3:'bird',4:'boat',5:'bottle',6:'bus',7:'car',8:'cat',9:......
  • 移动端兼容问题列表
    伪类:active生效要CSS伪类 :active 生效,只需要给document绑定 touchstart 或 touchend 事件<style>a{color:#000;}a:active{color:#fff;}</style><aherf=foo>bar</a><script>document.addEventListener('touchstart',fun......
  • python中列表推导式语法问题记录
    有问题代码:w=[0,1,2]e={0:[1,2],1:[3,4],2:[5,6]}r=[dimfordimine[i]foriinw]#这一段python代码有什么问题报错:Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>NameError:name'i'isnotdefined.Didyou......