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

Python对比浮点型嵌套列表 返回首个差值及对应名称的实现问题

实现思路
  • 调整isclose函数功能:不再打印中间内容,仅返回满足容差要求的差值,不满足时返回None
  • 移除全局差值存储逻辑,不需要缓存所有计算结果,遍历过程中只要命中第一个符合要求的差值就立刻终止所有循环,直接输出结果
  • 外层遍历取两个输入列表的最小长度,规避列表长度不一致导致的索引越界问题
  • 取消所有多余打印逻辑,仅输出最终匹配结果
实现代码
l_name = ["ALPHA", "BETA", "CHARLIE"]
liste1 = [[1, 2, 3.0001], [2,5.045,6.005], [3, 8.03, 9], [4, 10.5, 5.5]]
liste2 = [[1, 2, 3.0], [2,5.046,6.005], [3, 8.0029, 9], [4, 10.5, 5.55]]
abs_tol = 0.00001

def isclose(a, b, abs_tol):
    delta = abs(a-b)
    return delta if delta >= abs_tol else None

def find_first_delta():
    # 取两个列表的最小长度避免越界
    min_len = min(len(liste1), len(liste2))
    for i in range(min_len):
        for j in range(len(l_name)):
            delta = isclose(liste1[i][j], liste2[i][j], abs_tol)
            if delta is not None:
                # 命中第一个差值直接输出并终止函数,后续不再计算
                print(f"{l_name[j]} is the name with the first delta : {delta}")
                return
    # 如果遍历完所有元素都没有符合要求的差值
    print("No delta found matching the tolerance requirement")

find_first_delta()
输出结果
CHARLIE is the name with the first delta : 0.0001

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:00:01