How to find second largest number in a list?

前端 未结 14 1981
遇见更好的自我
遇见更好的自我 2020-12-06 15:38

So I have to find the second largest number from list. I am doing it through simple loops.

My approach is to divide a list into two parts and then find the largest n

14条回答
  •  再見小時候
    2020-12-06 15:50

    Second largest number in the list:

    alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    second_highest_number = sorted(list(set(alist)))[-2]
    

    If you only want the 2nd largest element in the list (in cases where the highest value may occur twice), just skip the set() and list() call.

    alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    second_highest_number = sorted(alist)[-2]
    

提交回复
热议问题