Python: take max N elements from some list

前端 未结 4 1392
后悔当初
后悔当初 2020-12-05 13:41

Is there some function which would return me the N highest elements from some list?

I.e. if max(l) returns the single highest element, sth. like m

4条回答
  •  甜味超标
    2020-12-05 14:11

    heapq.nlargest:

    >>> import heapq, random
    >>> heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100)))
    [1.9730767232998481, 1.9326532289091407, 1.7762926716966254]
    

提交回复
热议问题