Python 获取数组中最近的数字
Hi X1和X2来自输入文本框Python 获取数组中最近的数字,python,Python,Hi X1和X2来自输入文本框 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,
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.
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,则可以拒绝该值(假设这是过滤器的点)