首页 > 解决方案 > Python - 取略有不同值的索引

问题描述

我有兴趣获取另一个列表中包含的值的通用列表“L”的索引,称为“目标”。看起来很简单,但是如果我的目标列表的值略有不同,我不知道如何考虑这种差异。例如,如果在“L”列表中我的值为 1.9,而在目标中的值为 1.89,我想采用 1.9 的索引,因为它接近 1.89。我怎样才能做到这一点?

L = [0.4,0.5,0.55,0.78,0.9,1.1,1.8,1.9]
target = [0.55,0.9,1.09,1.89]
index = []
for i in target:
    index.append(L.index(i))
print(index)

预期输出:[2,4,5,7]

提前致谢!

标签: pythonlistindexing

解决方案


您可以使用math.isclose

import math

L = [0.4, 0.5, 0.55, 0.78, 0.9, 1.1, 1.8, 1.9]
target = [0.55, 0.9, 1.09, 1.89]

index = [i for i, e in enumerate(L) if any(math.isclose(e, t, abs_tol=0.05) for t in target)]
print(index)

输出

[2, 4, 5, 7]

上述方法的计算复杂度是O(nm),其中nm是列表 L 和目标的长度。target此外,您可以按以下方式进行排序O((n + m)logn)

def is_close_to_any(e, tgt):
    import bisect
    """Finds if any values are close in O(log n)"""
    point_before_insertion = max(0, bisect.bisect(tgt, e) - 1)

    # find two closest points
    values = tgt[point_before_insertion:point_before_insertion + 2]

    # return if any of the two is close
    return any(math.isclose(e, t, abs_tol=0.05) for t in values)


target = sorted(target)
index = [i for i, e in enumerate(L) if is_close_to_any(e, target)]
print(index)

输出 (使用排序和二分法)

[2, 4, 5, 7]

推荐阅读