sashkello
sashkello

Reputation: 17871

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

Upvotes: 0

Views: 273

Answers (2)

sashkello
sashkello

Reputation: 17871

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.

Upvotes: 0

mhlester
mhlester

Reputation: 23251

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.

Upvotes: 2

Related Questions