在Python中查找与特定值最接近的列表项
我有一个已经排好序的浮点数列表 y
,还有一个没有排序的浮点数列表 x
。
现在,我需要找出 x
中每个元素在 y
中位于哪个值之间,最好是通过 y
的索引来表示。举个例子,如果
y=[1,2,3,4,5]
x[0]=3.5
那么我希望 x
的索引 0
的输出是 (2,3)
,因为 3.5
在 y[2]
和 y[3]
之间。
基本上,这就像把 y
看作是区间的边界,然后把 x
按照这些区间进行分类,我想是这个意思。
那么,最简单的方法是什么呢?
3 个回答
0
问:有什么简单的方法可以做到这一点?
与其直接给你代码,我觉得你应该看看这个伪代码,并尝试自己写代码!如果你想学习,就不要只是从网上复制粘贴代码!
伪代码:
// Assume that when you have a tie,
// you put the number in the smallest range
// Here, b is between 2.1 and 3.5, instead of
// 3.5 and 4.1
float a[5] = {0.1, 1.1, 2.1, 3.5, 4.1}; // your y
float b = 3.5; // your x
// counter for the loop and indexes. Init i to second element
integer i = 1, prev = -1, next;
// while we are not in the end of the array
while(i < 5) {
// if b is in the range of ( a(i-1), a(i) ]
if(b <= a[i] && b > a[i - 1]) {
// mark the indexes
prev = i - 1;
next = i;
}
// go to next element
i++;
}
if(prev = -1)
print "Number is not between some numbers"
else
print "prev, next"
我认为这样可以帮助你理解要点,然后你就能选择最适合你的简单方法。
1
谢谢,我知道怎么一步一步地写代码。不过,我想要一个比较好看、简单、优雅的解决方案,现在我在用numpy.digitize(),我觉得这个方法挺好看的,而且效果也不错。
6
我会使用 zip
(在 Python 2.x 中用的是 itertools.izip
)来完成这个任务:
from itertools import islice#, izip as zip # if Python 2.x
def nearest_neighbours(x, lst):
for l1, l2 in zip(lst, islice(lst, 1, None)):
if l1 <= x <= l2:
return l1, l2
else:
# ?
下面是一个使用的例子:
>>> nearest_neighbours(3.5, range(1, 6))
(3, 4)
你需要决定如果 x
不在 lst
中的任何一对之间该怎么办(也就是替换 # ?
!)。如果你想要索引(虽然你的例子没有用到),可以试试 enumerate
。