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

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

    This will work, but I don't know if you want to retain the items in the list:

    max1 = max(myList)
    myList.remove(max1)
    max2 = max(myList)
    

    If you do, you can do this:

    max1 = max(myList)
    idx1 = myList.index(max1)
    myList.pop(idx1)
    
    max2 = max(myList)
    myList.insert(idx1,max1)
    

提交回复
热议问题