获取数组中最接近的数字

时间:2013-12-23 07:30:23

标签: python

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.

1 个答案:

答案 0 :(得分:2)

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的点),则可以拒绝此值。