将列表中的每个数字四舍五入到另一个列表中最接近的数字

时间:2018-07-18 20:52:28

标签: python list big-o rounding interval-tree

假设我有一个带有数字的特定列表x,还有另一个带有其他数字的列表yy的元素应该是x的元素,但是由于测量中的噪声,它们有些不同。我想为y的每个值找到最接近它的x的值。

我可以通过一些循环来执行此操作,并检查每个元素y[i]哪个元素x[j]最小化abs(x[j]-y[i]),但是我敢肯定,有一种更简单,更干净的方法去做这个。列表可能很大,所以我在这里寻找有效的代码。

到目前为止我写的代码是:

x_in = [1.1, 2.2, 3, 4, 6.2]
y_in = [0.9, 2, 1.9, 6, 5, 6, 6.2, 0.5, 0, 3.1]
desired_output = [1.1, 2.2, 2.2, 6.2, 4, 6.2, 6.2, 1.1, 1.1, 3]

y_out = []

for y in y_in:
    aux = [abs(l - y) for l in x_in]
    mn,idx = min( (aux[i],i) for i in range(len(aux)) )
    y_out.append(x_in[idx])

>>> y_out == desired_output
True

但是我不知道是否有更有效的方法来做到这一点...

编辑:

由于我的无知,我忘了根据我收到的评论澄清可能与之相关的事情。

  • x列表已排序。
  • x是唯一一个具有很大大小的列表:通常在500,000到1,000,000个元素之间。 y通常很小,少于10个元素。

6 个答案:

答案 0 :(得分:2)

鉴于x已排序,最有效的方法是使用bisect搜索最接近的值。只需在x值之间创建一个中点列表,然后对这些值进行二等分即可:

In [69]: mid_points = [(x1+x2)/2 for x1, x2 in zip(x[1:], x[:-1])]

In [70]: mid_points
Out[70]: [1.5, 2.5, 3.5, 4.5]

In [72]: [x[bisect.bisect(mid_points, v)] for v in y]
Out[72]: [1, 1, 4, 5, 2]

这将在O(Mlog(N)+N)时间运行,其中M = len(y),N = len(x)

(对于python2,请在from __future__ import division计算中使用float(x1+x2)/2或使用mid_points

答案 1 :(得分:1)

您可以使用lambda函数和列表理解功能快速完成此操作:

[min(x, key=lambda x:abs(x-a)) for a in y]

这将适用于浮点数,整数等。

答案 2 :(得分:0)

因此,我很快就总结出了这些东西,它们只获取所有差异,然后将它们从最小到最大排序。差异最小,然后从那里开始。

x = [1, 2, 3, 4, 5]
y = [1.1, 1.2, 3.6, 6.2, 2.1]

for y_index in range(len(y)):
    value_and_index= {}
    for x_index in range(len(x)):
        difference= y[y_index]-x[x_index]
        difference= difference*-1 if difference<0 else difference
        value_and_index[difference]= x_index
    y[y_index]= x[value_and_index[sorted(value_and_index.keys())[0]]]

print y # [1, 1, 4, 5, 2]

希望这对您有所帮助,编码愉快!

答案 3 :(得分:0)

我的尝试:

首先,我对X数组进行排序(如果尚未排序)。循环遍历每个y并计算每个x的绝对值,直到该绝对值大于先前的绝对值,然后停止for循环(因为数组X已排序):

x = sorted([1, 2, 3, 4, 5])
y = [1.1, 1.2, 3.6, 6.2, 2.1]

out = []
while y:
    current_value = y.pop()
    current_min = float('inf')
    current_x_value = None
    for v in x:
        temp_min = abs(current_value - v)
        if temp_min < current_min:
            current_min = temp_min
            current_x_value = v
        if temp_min > current_min:  # no need to iterate further, X is sorted
            break
    out.insert(0, current_x_value)
print(out)

输出:

[1, 1, 4, 5, 2]

答案 4 :(得分:0)

如果x已排序,请使用bisect

import bisect 
test_out=[]
max_x=max(x)
min_x=min(x)
for f in y:
    if f>=max_x:
        idx=-1
    elif f<=min_x:
        idx=0
    else:
        idx=bisect.bisect_left(x,f)
        if abs(x[idx-1]-f)<abs(x[idx]-f):
            idx-=1
    test_out.append(x[idx])

>>> test_out==desired_output
True

答案 5 :(得分:0)

接下来的假设:

  • 结果顺序无关紧要,

  • 我们正在使用 Python 3.3 +。

非常简单的解决方案可能看起来像

from itertools import repeat


def evaluate(expected_values, measurements):
    if not expected_values:
        raise ValueError('Expected values should be a non-empty sequence.')
    expected_values = sorted(expected_values)
    measurements = sorted(measurements)
    expected_iter = iter(expected_values)
    left_value = next(expected_iter)
    try:
        right_value = next(expected_iter)
    except StopIteration:
        # there is only one expected value
        yield from repeat(left_value,
                          len(measurements))
        return
    for evaluated_count, measurement in enumerate(measurements):
        while measurement > right_value:
            try:
                left_value, right_value = right_value, next(expected_iter)
            except StopIteration:
                # rest of the measurements are closer to max expected value
                yield from repeat(right_value,
                                  len(measurements) - evaluated_count)
                return

        def key(expected_value):
            return abs(expected_value - measurement)

        yield min([left_value, right_value],
                  key=key)

对于 Python3.3-,我们可以替换

yield from repeat(object_, times)

具有for这样的循环

for _ in range(times):
    yield object_

测试

>>> x_in = [1.1, 2.2, 3, 4, 6.2]
>>> y_in = [0.9, 2, 1.9, 6, 5, 6, 6.2, 0.5, 0, 3.1, 7.6, 10.4]
>>> y_out = list(evaluate(x_in, y_in))
>>> y_out
[1.1, 1.1, 1.1, 2.2, 2.2, 3, 4, 6.2, 6.2, 6.2, 6.2, 6.2]
相关问题