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