我有一个已排序的花车列表y
,以及未排序花车列表x
。在Python中查找最接近特定值的列表项目
现在,我需要找出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
到那些垃圾箱,我猜。
最简单的方法是什么?
我有一个已排序的花车列表y
,以及未排序花车列表x
。在Python中查找最接近特定值的列表项目
现在,我需要找出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
到那些垃圾箱,我猜。
最简单的方法是什么?
我会用(在Python 2.x的itertools.izip
)zip
来实现:
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
ISN什么'lst
(即替换# ?
!)之间的任何一对之间如果你想索引(虽然你的例子不使用它们),请与enumerate
玩一玩。
问:最简单的方法是什么?
而不是给你的代码,我想你应该看到这个伪代码和试图写你自己的代码!如果你想教育自己,不要从互联网复制粘贴代码!
伪代码:
// 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"
我认为这可以让你明白的点,然后可以选择适合你的最简单的方法。
谢谢 - 我意识到如何编码一步一步。然而,我正在寻找一个漂亮/简单/优雅的解决方案,现在我正在使用numpy.digitize(),这对我来说很漂亮,而且工作得很好。
尝试先写一些代码。你可能会惊讶自己并找到最简单的方法。 – IanAuld
你是否尝试过实际排序x? –