【问题标题】:How to find the index of n largest elements in a list or np.array, Python如何在列表或np.array中找到n个最大元素的索引,Python
【发布时间】:2013-05-28 12:57:34
【问题描述】:

是否有内置函数或非常简单的方法来查找列表或 numpy 数组中 n 个最大元素的索引?

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

找到最大的 5 个元素的索引?

我不止一次计算重复,输出应该是那些最大数字的索引列表

【问题讨论】:

标签: python arrays list


【解决方案1】:

可能是这样的:

>>> 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]

或者使用numpy,你可以使用argsort

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

argsort也是一个方法:

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

【讨论】:

  • 或者import heapq;heapq.nlargest(n, range(len(K)), key=lambda x: K[x])
【解决方案2】:

考虑以下代码,

 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])

如果你想忽略重复,那么使用 set() 如下,

 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])

希望其中一个能解决您的问题 :)

【讨论】:

    【解决方案3】:

    这应该可行:

    K = [1,2,2,4,5,5,6,10]
    num = 5
    print 'K %s.' % (sorted(K, reverse=True)[:num])
    

    【讨论】:

    • 这给出了值本身而不是它们的索引
    【解决方案4】:

    import headq

    然后使用函数nlargest()

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 2021-04-20
      • 2012-12-17
      • 2022-01-22
      • 2023-03-13
      相关资源
      最近更新 更多