简体   繁体   English

来自python列表的前n个最接近的数字

[英]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 ? 那么,如何从列表中选择与x0最接近的n数字? 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

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

Return a list with the n smallest elements from the dataset defined by iterable. 返回一个列表,其中包含iterable定义的数据集中的n个最小元素。 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] key(如果提供)指定一个参数的函数,该函数用于从iterable中的每个元素中提取比较键:key = str.lower等效于: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 . 这会减少开销,因为它会丢弃超过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. 它在时间复杂度方面比heapq.nsmallest慢,但是开销较少,因此对于小型列表更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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