2014-05-19 70 views
2

我有一个已排序的花车列表y,以及未排序花车列表x在Python中查找最接近特定值的列表项目

现在,我需要找出x中的每个元素,它位于哪个值y之间,最好是索引y。因此,举例来说,如果

y=[1,2,3,4,5] 

x[0]=3.5 

我需要对指数的x0输出为(2,3),因为3.5y[2]y[3]之间。

基本上,它看到y作为垃圾箱边缘和排序x到那些垃圾箱,我猜。

最简单的方法是什么?

+5

尝试先写一些代码。你可能会惊讶自己并找到最简单的方法。 – IanAuld

+0

你是否尝试过实际排序x? –

回答

4

我会用(在Python 2.x的itertools.izipzip来实现:

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玩一玩。

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(),这对我来说很漂亮,而且工作得很好。

相关问题