python知识点梳理--找到最大或者最小的N个元素

python知识点梳理–找到最大或者最小的N个元素

问题
我们想在列表中找到最大或者最小的N个元素.
解决方法
我们可以使用heapq模块中的nlargest()或者nsmallest()函数来完成这个目标.
示例1

import heapq
nums = [3, -1, 2, 9, 12, 4]
N = 3
element_smallest = heapq.nsmallest(N, nums)
print("the smallest {} elements is {}".format(N, element_smallest))

以上代码的运行结果是the smallest 3 elements is [-1, 2, 3].
注意: 返回的结果是从小到大排序的
示例2

import heapq
nums = [3, -1, 2, 9, 12, 4]
N = 3
element_largest = heapq.nlargest(N, nums)
print("the largest {} elements is {}".format(N, element_largest))

以上代码的运行结果是the largest 3 elements is [12, 9, 4].
注意: 返回的结果是从大到小排序的

如果需要在字典中按某个key-value来取出最大或者最小的N个元素. 也可以使用nlargest()或者nsmallest()函数, 具体做法是传入一个key,和sort()等函数的做法一致,一般为一个lambda表达式.
示例3

portfolio = [
    {'name': 'IBM', 'shares': 100, 'price':91.1},
    {'name': 'Apple', '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}
]
cheapest_three = heapq.nlargest(3, portfolio, key = lambda x: x['price'])
print(cheapest_three)

猜你喜欢

转载自blog.csdn.net/weixin_37486217/article/details/84019905
今日推荐