Finding the nth smallest number in a list?

后端 未结 2 1687
抹茶落季
抹茶落季 2020-12-11 23:02

i need a efficient way of getting the nth smallest number AND its index in a list containing up to 15000 enties (so speed is not super crucial).

I sadly can\'t use n

相关标签:
2条回答
  • 2020-12-11 23:53

    Use enumerate to store the original position, then sort by the value:

    original_list = [36, 44, 23, 24, 47, 19, 49, 36, 30, 3]
    sorted_lookup = sorted(enumerate(original_list), key=lambda i:i[1])
    position, value = sorted_lookup[4] # 4 is my "n"
    

    sorted_lookup in my example is:

    [(9, 3), (5, 19), (2, 23), (3, 24), (8, 30), (0, 36), (7, 36), (1, 44), (4, 47), (6, 49)]
    

    And position is 8, value is 30

    0 讨论(0)
  • 2020-12-11 23:55

    use heapq.nsmallest (and enumerate to get the index):

    nums = [random.randint(1,1000000) for _ in range(10000)]
    
    import heapq
    import operator
    
    heapq.nsmallest(10,enumerate(nums),key=operator.itemgetter(1))
    Out[26]: 
    [(5544, 35),
     (1702, 43),
     (6547, 227),
     (1540, 253),
     (4919, 360),
     (7993, 445),
     (1608, 495),
     (5832, 505),
     (1388, 716),
     (5103, 814)]
    
    0 讨论(0)
提交回复
热议问题