企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC=1,5] >[success] # 纯列表三种求最大/小值方法 如果只是单单判断,单个最大值,最小值用max/min,当求一组最大值最小值的时候,分两种,如果一组长度和列表的长度基本一致,推荐先排序在切片,相反使用堆 >[danger] ##### 求单个的最大/小值 -- max/min ~~~ nums = [1,1,1,23,7,5,6,10,12,13,45,88,69,30] print (max(nums),min(nums)) 打印结果: 88 1 ~~~ >[danger] ##### 求一组最大/小值-heapq ~~~ import heapq nums = [ {'name': "aaa", "shares": 100, "price": 90.1}, {'name': "bbb", "shares": 99, "price": 92.1}, {'name': "ccc", "shares": 101, "price": 93.1}, {'name': "ddd", "shares": 102, "price": 94.1}, ] print(heapq.nsmallest(3,nums,key=lambda k: k['price'])) print(heapq.nlargest(3,nums,key=lambda k: k['price'])) 打印结果: [{'shares': 100, 'name': 'aaa', 'price': 90.1}, {'shares': 99, 'name': 'bbb', 'price': 92.1}, {'shares': 101, 'name': 'ccc', 'price': 93.1}] [{'shares': 102, 'name': 'ddd', 'price': 94.1}, {'shares': 101, 'name': 'ccc', 'price': 93.1}, {'shares': 99, 'name': 'bbb', 'price': 92.1}] ~~~ >[danger] ##### 求一组最大/小值-sorted ~~~ nums = [1,1,1,23,7,5,6,10,12,13,45,88,69,30] print (sorted(nums)[0:3],sorted(nums,reverse=True)[0:3]) 打印结果: [1, 1, 1] [88, 69, 45] ~~~ >[success] # 列表嵌套字典 >[danger] ##### 求单个的最大/小值 -- max/min ~~~ nums = [ {'name': "aaa", "shares": 100, "price": 90.1}, {'name': "bbb", "shares": 99, "price": 92.1}, {'name': "ccc", "shares": 101, "price": 93.1}, {'name': "ddd", "shares": 102, "price": 94.1}, ] print(max(nums,key=lambda k: k['price'])) print(min(nums,key=lambda k: k['price'])) 打印结果: {'name': 'ddd', 'shares': 102, 'price': 94.1} {'name': 'aaa', 'shares': 100, 'price': 90.1} ~~~ >[danger] ##### 求一组最大/小值-heapq ~~~ import heapq nums = [1,1,1,23,7,5,6,10,12,13,45,88,69,30] print (heapq.nlargest(3,nums),heapq.nsmallest(3,nums)) 打印结果: [88, 69, 45] [1, 1, 1] ~~~ >[danger] ##### 求一组最大/小值-sorted ~~~ import time import heapq nums = [ {'name': "aaa", "shares": 100, "price": 90.1}, {'name': "bbb", "shares": 99, "price": 92.1}, {'name': "ccc", "shares": 101, "price": 93.1}, {'name': "ddd", "shares": 102, "price": 94.1}, ] print(sorted(nums,key=lambda k: k['price'],reverse=True)[0:2]) print(sorted(nums,key=lambda k: k['price'])[0:2]) 打印结果: [{'price': 94.1, 'name': 'ddd', 'shares': 102}, {'price': 93.1, 'name': 'ccc', 'shares': 101}] [{'price': 90.1, 'name': 'aaa', 'shares': 100}, {'price': 92.1, 'name': 'bbb', 'shares': 99}] ~~~