2014-05-19 72 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(),這對我來說很漂亮,而且工作得很好。

相關問題