python - 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]
提前致谢!
解决方案
您可以使用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)
,其中n
和m
是列表 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]
推荐阅读
- mysql - 使用每个帐户的最近日期的所有帐户的值总和
- c# - 如何有效地比较大量照片以找到重复项
- java - GenCollectForAllocation 是什么意思?
- q# - 访问模拟器或跟踪模拟器的调用图
- c# - 如何在 OData 中全局更改 MaxExpansionDepth 设置
- python - 在 matplotlib 中将绘图附加到 HTML 文件
- javascript - 反应:链接到另一个 html 页面上的 div
- c# - 在 EF 核心中搭建脚手架时出现 sql 连接字符串错误?
- javascript - 将 css 颜色转换为 Javascript 颜色
- python-3.x - 如何在 python 的 Flask 中创建实用程序类的通用实例?