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

Pytest中如何校验值为numpy数组的两个字典是否相等

pytest校验含numpy数组的字典相等方法

报错原因

直接使用==比较两个numpy数组时,返回的是逐元素对比的布尔数组,Python无法直接将多元素布尔数组转为单个布尔值,因此触发ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()错误。

最简实现方案

直接使用numpy内置的测试断言函数即可,无需自行遍历字典:

  • 整数/精确值完全匹配场景,使用np.testing.assert_equal:
import numpy as np

def test_init():
    tbl = DataTable(a=[1,2,4], b=[4,5,6]) 
    # 直接传入实际字典和期望字典,一行完成校验
    np.testing.assert_equal(tbl._data, {"a":np.array([1,2,4]), "b":np.array([4,5,6])})
  • 浮点类型数组存在精度误差场景,使用np.testing.assert_allclose,可自定义误差阈值:
# rtol为相对误差,atol为绝对误差,可根据需求调整
np.testing.assert_allclose(tbl._data, {"a":np.array([1,2,4]), "b":np.array([4,5,6])}, rtol=1e-05, atol=1e-08)

该方案的优势:

  • 自动校验字典的键集合是否完全一致,缺键/多键都会直接抛出错误
  • 自动逐元素对比每个键对应的numpy数组,形状不一致、数值不匹配都会给出明确的错误提示,直接定位问题位置
  • 无需手动编写遍历逻辑,代码简洁不易出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 13:36:04