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

前端 未结 2 1375
北海茫月
北海茫月 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 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]
    

提交回复
热议问题