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

如何比较嵌套浮点型列表?解决assertListEqual断言失败问题

嵌套浮点列表断言的解决办法

直接用assertListEqual没法通过断言,因为浮点数存在精度误差——哪怕数值逻辑上相等,二进制存储的微小差异也会导致断言失败。下面是几种可行的解决方式:

1. 自定义嵌套比较逻辑

自己实现递归遍历列表的函数,对每个元素做针对性比较:整数直接判断相等,浮点数用assertAlmostEqual指定精度阈值。示例代码:

import unittest

def assert_nested_list_equal(list1, list2):
    assert len(list1) == len(list2), "列表长度不一致"
    for item1, item2 in zip(list1, list2):
        if isinstance(item1, list) and isinstance(item2, list):
            assert_nested_list_equal(item1, item2)
        elif isinstance(item1, float) and isinstance(item2, float):
            unittest.TestCase().assertAlmostEqual(item1, item2, places=6)
        else:
            assert item1 == item2, f"{item1} != {item2}"

llof_1 = [ [15, 16, 6.123], [23, 24, 32.041] ]
llof_2 = [ [15, 16, 6.123000000000001], [23, 24, 32.04100000000001] ]
assert_nested_list_equal(llof_1, llof_2)  # 不会报错

2. 使用numpy的近似断言

如果项目中已经用到numpy,可以借助np.testing.assert_allclose,它支持嵌套结构,还能灵活设置相对/绝对误差:

import numpy as np

llof_1 = [ [15, 16, 6.123], [23, 24, 32.041] ]
llof_2 = [ [15, 16, 6.123000000000001], [23, 24, 32.04100000000001] ]
np.testing.assert_allclose(llof_1, llof_2, rtol=1e-9, atol=0)  # 断言通过

3. 用pytest的近似匹配

如果用pytest框架,可以直接用pytest.approx,语法更简洁,对嵌套列表天然支持:

import pytest

llof_1 = [ [15, 16, 6.123], [23, 24, 32.041] ]
llof_2 = [ [15, 16, 6.123000000000001], [23, 24, 32.04100000000001] ]
assert llof_1 == pytest.approx(llof_2)  # 断言通过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 00:22:28