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

前端 未结 2 1374
北海茫月
北海茫月 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 )
    
    0 讨论(0)
  • 2021-02-14 18:12

    Use heapq.nlargest:

    >>> import heapq
    >>> [i
    ...     for x, i
    ...     in heapq.nlargest(
    ...         3,
    ...         ((x, i) for i, x in enumerate((0,5,8,7,2,4,3,9,1))))]
    [7, 2, 3]
    
    0 讨论(0)
提交回复
热议问题