[英]Finding the position in a list of the closest value to a given number
I have a list of values, not necessarily sorted, for example 我有一个值列表,例如,不一定排序
list=[1.1,0.7,1.8,2.,1.65]
and I want to find the position in the list of the closest value to a given number, for example a=1.4
. 我想在列表中找到与给定数字最接近的值的位置,例如
a=1.4
。 It does not matter whether the value in the list is larger or smaller than the given value. 列表中的值是大于还是小于给定值无关紧要。 Of course, one way to do it is with a
for
loop 当然,一种方法是使用
for
循环
import numpy as np
d=100.
i=0
for s in list:
if np.abs(s-a)<d:
pos=i
d=np.abs(s-a)
i+=1
print pos
but in python there must be a much better way. 但在python中必须有一个更好的方法。 How can I do it more synthetically ?
我怎样才能更合成呢? What if the values are instead sorted?
如果值被排序怎么办?
You can convert this to a numpy array and calculate the index of the minimum absolute difference between the items and target
, like: 您可以将其转换为numpy数组并计算项目与
target
之间的最小绝对差异的索引,如:
def min_diff_pos(array_like, target):
return np.abs(np.array(array_like)-target).argmin()
For example: 例如:
>>> min_diff_pos([1.1,0.7,1.8,2.,1.65], 1.1)
0
>>> min_diff_pos([1.1,0.7,1.8,2.,1.65], 1.8)
2
>>> min_diff_pos([1.1,0.7,1.8,2.,1.65], 1.7)
4
>>> min_diff_pos([1.1,0.7,1.8,2.,1.65], 1.79)
2
If the values are sorted, we can use a binary search algorithm, and then look at the two items that are near the insertion point. 如果值已排序,我们可以使用二进制搜索算法,然后查看插入点附近的两个项目。 In that case it is the closest of these two.
在这种情况下,它是这两者中最接近的。 This makes a lookup O(log n) instead of O(n) :
这使得查找O(log n)而不是O(n) :
def min_diff_pos_sorted(sorted_array, target):
idx = np.searchsorted(sorted_array, target)
idx1 = max(0, idx-1)
return np.abs(np.array(sorted_array[idx1:idx+1])-target).argmin() + idx1
For example: 例如:
>>> data = np.array([0.7, 1.1, 1.65, 1.8, 2.0])
>>> min_diff_pos_sorted(data, 0.7)
0
>>> min_diff_pos_sorted(data, 0.8)
0
>>> min_diff_pos_sorted(data, 0.9)
0
>>> min_diff_pos_sorted(data, 1.0)
1
>>> min_diff_pos_sorted(data, 1.1)
1
>>> min_diff_pos_sorted(data, 1.2)
1
>>> min_diff_pos_sorted(data, 1.3)
1
>>> min_diff_pos_sorted(data, 1.4)
2
a pretty straitforward solution without numpy or other third party tools: 一个非常简单的解决方案,没有numpy或其他第三方工具:
values = [1.1, 0.7, 1.8, 2., 1.65]
def get_min_pos(values, referencevalue):
d = [(referencevalue - x)**2 for x in values]
return d.index(min(d))
a first test: 第一次测试:
testvalues = values
for value in testvalues:
expected_pos = values.index(value)
pos = get_min_pos(values=values, referencevalue=value)
assert pos == expected_pos
# list of testvalue and expected indox pos for the value
testvalues = [(1.0, 0), (0.8, 1), (0.9, 0), (0.89, 1), ]
for value, expected_pos in testvalues:
value = get_min_pos(values=values, referencevalue=value)
assert value == expected_pos
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.