You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何获取列表中与目标列表元素近似值对应的索引

实现思路

原代码使用精确匹配list.index()自然无法匹配存在微小误差的数值,我们改为对每个目标值计算与L中所有元素的差值绝对值,取差值最小的元素对应的索引即可,也可自定义容差阈值过滤误差过大的无效匹配。

基础实现(无第三方依赖)

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 = []
# 可按需调整允许的最大误差,不需要校验的话可以删除容差相关逻辑
max_tolerance = 0.1

for t in target:
    # 计算当前目标值和L所有元素的差值绝对值
    diff_list = [abs(num - t) for num in L]
    min_diff = min(diff_list)
    # 可选:超出容差范围判定为无匹配,示例中的数值都在容差范围内
    if min_diff <= max_tolerance:
        min_index = diff_list.index(min_diff)
        index.append(min_index)

print(index)
# 输出:[2, 4, 5, 7]

大数据量优化实现(基于numpy)

如果L和target的长度很大,用numpy的向量化运算可以大幅提升效率:

import numpy as np

L = np.array([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 = [np.argmin(np.abs(L - t)) for t in target]

print(index)
# 输出:[2, 4, 5, 7]

内容的提问来源于stack exchange,提问作者John_maddon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:15:03