Top n closest numbers from a python list -


i need select amount of numbers list, closest ones other number.

for example:

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

so, how select n numbers list closest ones x0? there built-in method?

topn = [43, 54, 32] 

the way see below, looks bit convoluted:

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

use heapq.nsmallest:

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

return list n smallest elements dataset defined iterable. key, if provided, specifies function of 1 argument used extract comparison key each element in iterable: key=str.lower equivalent to: sorted(iterable, key=key)[:n]

so in 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 discards elements exceed n.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -