美文网首页
python 一个集合中获得最大或者最小的 N 个元素列表

python 一个集合中获得最大或者最小的 N 个元素列表

作者: 小乔与周瑜 | 来源:发表于2019-08-07 11:35 被阅读0次

    怎样从一个集合中获得最大或者最小的 N 个元素列表?

    heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题。

    import  heapq

    mums = [1,2,23,4,-4,22]

    heapq.nlargest(3,nums)#prints[23,22,4]

    heapq.nsmallest(3,nums) #prints[-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'])

    heapq 标准库连接

    https://www.jianshu.com/p/801318c77ab5

    相关文章

      网友评论

          本文标题:python 一个集合中获得最大或者最小的 N 个元素列表

          本文链接:https://www.haomeiwen.com/subject/tjfodctx.html