简体   繁体   中英

Top n closest numbers from a python list

I often need to select a certain amount of numbers from a list, so that they are the closest ones to some other certain number.

For example:

x0 = 45
n = 3
mylist = [12,32,432,43,54,234,23,543,2]

So, how do I select n numbers from the list which are the closest ones to x0 ? Is there some built-in method?

topN = [43, 54, 32]

The way I see is below, however it looks a bit convoluted:

diffs = sorted([(abs(x - x0), x) for x in mylist])
topN = [d[1] for d in diffs[:n]]

Use heapq.nsmallest :

heapq.nsmallest(n, iterable[, key])

Return a list with the n smallest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower Equivalent to: sorted(iterable, key=key)[:n]

So in your particular case:

import heapq
x0 = 45
n = 3
mylist = [12,32,432,43,54,234,23,543,2]
heapq.nsmallest(n, mylist, key=lambda x: abs(x-x0))

This uses less overhead because it discards elements as they exceed n .

Can be alternatively done using sorting by custom function:

sorted(mylist, key = lambda x : abs(x-x0))[:n]

It is slower than heapq.nsmallest in terms of time complexity, however has less overhead and thus is more efficient for small lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM