How to find the 1st, 2nd, 3rd highest values in a list in Python

前端 未结 2 1373
北海茫月
北海茫月 2021-02-14 17:36

I know how to find the 1st highest value but don\'t know the rest. Keep in mind i need to print the position of the 1st 2nd and 3rd highest value.Thank You and try to keep it si

2条回答
  •  执笔经年
    2021-02-14 17:56

    This will print a list of the 3 highest items, each paired with its index:

    lst = [9,7,43,2,4,7,8,5,4]
    print( sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )[:3] )
    

    Things are a bit more complicated if the same value can appear multiple times (this will show the highest position for a value):

    lst = [9,7,43,2,4,7,8,5,4]
    ranks = sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )
    values = []
    posns = []
    for x,i in ranks:
        if x not in values:
            values.append( x )
            posns.append( i )
            if len(values) == 3:
                break
    print zip( values, posns )
    

提交回复
热议问题