how to efficiently get the k bigger elements of a list in python

后端 未结 5 620
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 06:58

What´s the most efficient, elegant and pythonic way of solving this problem?

Given a list (or set or whatever) of n elements, we want to get the k biggest ones. ( Yo

5条回答
  •  眼角桃花
    2020-12-05 07:30

    You can use the heapq module.

    >>> from heapq import heapify, nlargest
    >>> l = [9,1,6,4,2,8,3,7,5]
    >>> heapify(l)
    >>> nlargest(3, l)
    [9, 8, 7]
    >>> 
    

提交回复
热议问题