如何比较由浮点数列表构成的列表?
我想把一个包含浮点数的列表的列表与一个基线进行比较:
所以对于这两个列表,
llof_1 = [ [15, 16, 6.123], [23, 24, 32.041] ]
llof_2 = [ [15, 16, 6.123000000000001], [23, 24, 32.04100000000001] ]
我希望能够:
assertListEqual(llof_1, llof_2)
是否可能?目前我得到 AssertionError: Lists differ
解决方案
如果你写的代码中这些列表应该被视为相等,尽管它们实际上并不相等,请编写一个 自定义断言类,这样你就拥有实现你代码需要的任何非标准断言的全部自由。
如果你确定你正在处理的是浮点数列表的列表,那么你可以直接写出:
def assertApproxListEqual(self, l1, l2):
if len(l1) is not len(l2):
raise AssertionError("lists have different length")
for a, b in zip(l1, l2):
if len(a) is not len(b):
raise AssertionError(f"sublists {a}/{b} have different lengths")
for x, y in zip(a, b):
if not isinstance(x, (int, float)):
raise AssertionError(f"sublist {a} contains non-number {x}")
if not isinstance(y, (int, float)):
raise AssertionError(f"sublist {b} contains non-number {y}")
if abs(x-y) > 1e-9:
raise AssertionError(f"values {x}/{y} in {a}/{b} are not approximately equal")
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。