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

后端 未结 15 786
心在旅途
心在旅途 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:30

    Sort the list, and if list is not null, extract last two element

    >>> a=[0,6,8,5,10,5]
    >>> a.sort()
    >>> a
    [0, 5, 5, 6, 8, 10]
    >>> if a:
    ...  print a[-1],a[-2]
    ... 
    10 8
    

    Simple and most efficient:)

    Now if sorting is not required, find max, remove max, find max again

    >>> a=[0,6,8,5,10,5]
    >>> max(a)
    10
    >>> a.remove(max(a))
    >>> max(a)
    8
    >>> 
    

    Of course, you will lose the original list but you can create a temporary list as well.

提交回复
热议问题