unittest - 不考虑顺序比较列表 [英] unittest - compare list irrespective of order

查看:43
本文介绍了unittest - 不考虑顺序比较列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对两个列表值列表进行单元测试:

I am doing a unit test on two list of list values:

self.assertEqual(sale, [['1',14], ['2',5], ['3',7], ['4',1]])

但它给出了以下错误:

AssertionError: Lists differ: [['1', 14], ['4', 1], ['2', 5], ['3', 7]] != [['1'
, 14], ['2', 5], ['3', 7], ['4', 1]]

First differing element 1:
['4', 1]
['2', 5]

- [['1', 14], ['4', 1], ['2', 5], ['3', 7]]
+ [['1', 14], ['2', 5], ['3', 7], ['4', 1]]

我怎样才能让这个场景通过,防止assertEqual函数来避免检查列表中元素的顺序.

How can I make this scenario pass, Prevent the assertEqual function to avoid checking the order of the elements in the list.

推荐答案

由于 Python 列表会跟踪顺序,因此您需要某种方法来确保项目的顺序相同.

Since Python lists keep track of order, you'll need some way to make sure the items are in the same order.

如果所有项目都是唯一的,则集合可能会起作用.如果它们不是唯一的,您将丢失有关重复项的信息.

A set might work, if all items are unique. If they aren't unique you'll lose information on the duplicates.

在比较之前对列表进行排序可能是您最好的选择.它将保持所有数据完整无缺,并将它们以相同的顺序放在每个列表中.

Sorting the lists before you compare them will probably be your best bet. It will keep all the data intact, and put them in the same order in each list.

这里是 Python 3 中列表的不同内置排序方法的链接.https://docs.python.org/3/howto/sorting.html

Here is a link to the different built in sorting methods for lists in Python 3. https://docs.python.org/3/howto/sorting.html

这篇关于unittest - 不考虑顺序比较列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆