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

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

    
    my_list = [20, 1, 9, 5, 10, 3, 4, 2, 11, 21, 2]
    
    max2 = 0
    max1 = 0
    for i in my_list:
        if i > max1:
            max1 = i
        elif max2 < i < max1:
            max2 = i
    
    print(f'max1: {max1}; max2: {max2}')
    max1: 21; max2: 11
    
    

提交回复
热议问题