How to find the index of n largest elements in a list or np.array, Python

前端 未结 4 684
夕颜
夕颜 2021-02-05 09:05

Is there a built-in function or a very simple way of finding the index of n largest elements in a list or a numpy array?

K = [1,2,2,4,5,5,6,10]

相关标签:
4条回答
  • 2021-02-05 09:51

    Maybe something like:

    >>> K
    [4, 5, 1, 6, 2, 5, 2, 10]
    >>> sorted(range(len(K)), key=lambda x: K[x])
    [2, 4, 6, 0, 1, 5, 3, 7]
    >>> sorted(range(len(K)), key=lambda x: K[x])[-5:]
    [0, 1, 5, 3, 7]
    

    or using numpy, you can use argsort:

    >>> np.argsort(K)[-5:]
    array([0, 1, 5, 3, 7])
    

    argsort is also a method:

    >>> K = np.array(K)
    >>> K.argsort()[-5:]
    array([0, 1, 5, 3, 7])
    >>> K[K.argsort()[-5:]]
    array([ 4,  5,  5,  6, 10])
    
    0 讨论(0)
  • 2021-02-05 09:54

    Consider the following code,

     N=5
     K = [1,10,2,4,5,5,6,2]
     #store list in tmp to retrieve index
     tmp=list(K)
     #sort list so that largest elements are on the far right
     K.sort()
     #To get the 5 largest elements
     print K[-N:]
     #To get the 5th largest element
     print K[-N]
     #get index of the 5th largest element
     print tmp.index(K[-N])
    

    If you wish to ignore duplicates, then use set() as follows,

     N=5
     K = [1,10,2,4,5,5,6,2]
     #store list in tmp to retrieve index
     tmp=list(K)
     #sort list so that largest elements are on the far right
     K.sort()
     #Putting the list to a set removes duplicates
     K=set(K)
     #change K back to list since set does not support indexing
     K=list(K)
     #To get the 5 largest elements
     print K[-N:]
     #To get the 5th largest element
     print K[-N]
     #get index of the 5th largest element
     print tmp.index(K[-N])
    

    Hopefully one of them covers your question :)

    0 讨论(0)
  • 2021-02-05 10:01

    This should work:

    K = [1,2,2,4,5,5,6,10]
    num = 5
    print 'K %s.' % (sorted(K, reverse=True)[:num])
    
    0 讨论(0)
  • 2021-02-05 10:01

    import headq

    Then use function nlargest()

    0 讨论(0)
提交回复
热议问题