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

Python中如何查找列表间误差≤0.1的近似匹配值?

在两个列表中查找误差范围内的近似浮点数

问题根源

直接用i in real_list会进行精确浮点数匹配,但示例中两个列表的元素只是近似相等(差值在±0.01到±0.1之间),并非严格相等,所以无法匹配。

解决方案1:按步长生成候选值匹配

按照你提到的「以0.01为步长、误差不超过0.1」的思路,可为每个list_2中的元素生成所有可能的候选值(从i-0.1到i+0.1,步长0.01),再检查候选值是否存在于real_list中。注意由于浮点数精度问题,建议先将列表元素和候选值四舍五入到两位小数再判断:

real_list = [1.94, 4.72, 8.99, 5.37, 1.33]
list_2 = [1.86, 4.78, 8.91, 5.41, 1.30]

# 先将real_list的元素四舍五入到两位小数,避免浮点数精度干扰
real_rounded = [round(num, 2) for num in real_list]

for num in list_2:
    found = False
    # 生成从num-0.1到num+0.1,步长0.01的所有候选值,四舍五入到两位小数
    for delta in range(-10, 11):
        candidate = round(num + delta * 0.01, 2)
        if candidate in real_rounded:
            found = True
            break
    print("found" if found else "not found")

解决方案2:直接判断差值范围(更高效)

无需生成大量候选值,直接计算两个元素的绝对差值,判断是否在你需要的范围内(≥0.01且≤0.1):

real_list = [1.94, 4.72, 8.99, 5.37, 1.33]
list_2 = [1.86, 4.78, 8.91, 5.41, 1.30]

for num in list_2:
    found = False
    for real_num in real_list:
        diff = abs(num - real_num)
        # 判断差值是否在0.01到0.1之间
        if 0.01 <= diff <= 0.1:
            found = True
            break
    print("found" if found else "not found")

补充说明

如果列表元素数量很大,方案2的效率会远高于方案1——方案1需要生成21个候选值进行查找,而方案2只需遍历一次real_list。另外,若允许差值包含0(即精确匹配也视为有效),只需把判断条件改成diff <= 0.1即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:35:17