2013-12-23 34 views
0

Hi X1和X2來自Entry Text Box。獲取陣列中最接近的數字

If user select X1 = 4500 and X2 = 8500 
It will locate the nearest number from appliedField. So 4500 will be 4500. 
and 8500 will be 8000. 

appliedField = [4500, 5000, 5500, 8000, 10000,11000,12000] 
signal = [1,2,3,4,5,6,7,8,9,10,11,12] 

我如何處理代碼。

X1 = 4500 X2 = 8500 # Gotten from Entry Text Box (User Key In) 

appliedField = [4500, 5000, 5500, 8000, 10000,11000,12000] 
signal = [1,2,3,4,5,6,7,8,9,10,11,12] 

tuple_list = zip(appliedField, signal) 

filteredOP = (filter(lambda x: x1+2000 >= x[0] >= x1-2000, tuple_list))[0] 
filteredOP2 = (filter(lambda x: x2+2000 >= x[0] >= x2-2000, tuple_list))[0] 

問題是,如果用戶選擇X2 = 11000,

I would want it to be 11000. Rather than 10000 or 12000. 
How can i do that?? 
I need it to be as near as the number obtained from entry text box as possible. 

回答

3

min需要key參數,它可能是有用的:

>>> X = 4500 
>>> min(tuple_list,key=lambda x: abs(X-x[0])) 
(4500, 1) 
>>> X = 8500 
>>> min(tuple_list,key=lambda x: abs(X-x[0])) 
(8000, 4) 
>>> X = 11000 
>>> min(tuple_list,key=lambda x: abs(X-x[0])) 
(11000, 6) 

然後,如果它是你可以拒絕該值從X以上2000(假設這是您的filter的點)。