Retrieve the two highest item from a list containing 100,000 integers

后端 未结 15 804
心在旅途
心在旅途 2020-12-13 17:55

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?

15条回答
  •  心在旅途
    2020-12-13 18:18

    Use heapq.nlargest. This is the most flexible approach in case you ever want to handle more than just the top two elements.

    Here's an example.

    >>> import heapq
    >>> import random
    >>> x = range(100000)
    >>> random.shuffle(x)
    >>> heapq.nlargest(2, x)
    [99999, 99998]
    

提交回复
热议问题