如何在Python中断言两个列表包含相同的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12813633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assert two list contain the same elements in Python?
提问by satoru
When writing test cases, I often need to assert that two list contain the same elements without regard to their order.
在编写测试用例时,我经常需要断言两个列表包含相同的元素而不考虑它们的顺序。
I have been doing this by converting the lists to sets.
我一直通过将列表转换为集合来做到这一点。
Is there any simpler way to do this?
有没有更简单的方法来做到这一点?
EDIT:
编辑:
As @MarkDickinson pointed out, I can just use TestCase.assertItemsEqual.
正如@MarkDickinson 指出的,我可以只使用TestCase.assertItemsEqual。
Notes that TestCase.assertItemsEqualis new in Python2.7.
If you are using an older version of Python, you can use unittest2- a backport of new features of Python 2.7.
TestCase.assertItemsEqualPython2.7 中新增的注释。如果您使用的是旧版本的 Python,您可以使用unittest2- Python 2.7 新功能的反向移植。
采纳答案by flazzarini
As of Python 3.2 unittest.TestCase.assertItemsEqual(doc) has been replaced by unittest.TestCase.assertCountEqual(doc) which does exactly what you are looking for, as you can read from the python standard library documentation. The method is somewhat misleadingly named but it does exactly what you are looking for.
从 Python 3.2 unittest.TestCase.assertItemsEqual( doc) 开始,unittest.TestCase.assertCountEqual( doc)已替换为( doc),它完全符合您的要求,正如您可以从 python标准库文档中读取的那样。该方法的名称有些误导,但它确实符合您的要求。
a and b have the same elements in the same number, regardless of their order
a 和 b 具有相同数量的相同元素,无论它们的顺序如何
Here a simple example which compares two lists having the same elements but in a different order.
这是一个简单的例子,它比较了两个具有相同元素但顺序不同的列表。
- using
assertCountEqualthe test will succeed - using
assertListEqualthe test will fail due to the order difference of the two lists
- 使用
assertCountEqual测试会成功 assertListEqual由于两个列表的顺序不同,使用测试会失败
Here a little example script.
这里有一个小示例脚本。
import unittest
class TestListElements(unittest.TestCase):
def setUp(self):
self.expected = ['foo', 'bar', 'baz']
self.result = ['baz', 'foo', 'bar']
def test_count_eq(self):
"""Will succeed"""
self.assertCountEqual(self.result, self.expected)
def test_list_eq(self):
"""Will fail"""
self.assertListEqual(self.result, self.expected)
if __name__ == "__main__":
unittest.main()
Side Note :Please make sure that the elements in the lists you are comparing are sortable.
旁注:请确保您要比较的列表中的元素是可排序的。
回答by inspectorG4dget
Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:
将您的列表转换为集合会告诉您它们包含相同的元素。但是这种方法不能确认它们包含相同数量的所有元素。例如,在这种情况下,您的方法将失败:
L1 = [1,2,2,3]
L2 = [1,2,3,3]
You are likely better off sorting the two lists and comparing them:
您可能最好对两个列表进行排序并进行比较:
def checkEqual(L1, L2):
if sorted(L1) == sorted(L2):
print "the two lists are the same"
return True
else:
print "the two lists are not the same"
return False
Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists
请注意,这不会改变两个列表的结构/内容。相反,排序会创建两个新列表
回答by defuz
Slightly faster version of the implementation (If you know that most couples lists will have different lengths):
稍微快一点的实现版本(如果你知道大多数情侣列表会有不同的长度):
def checkEqual(L1, L2):
return len(L1) == len(L2) and sorted(L1) == sorted(L2)
Comparing:
比较:
>>> timeit(lambda: sorting([1,2,3], [3,2,1]))
2.42745304107666
>>> timeit(lambda: lensorting([1,2,3], [3,2,1]))
2.5644469261169434 # speed down not much (for large lists the difference tends to 0)
>>> timeit(lambda: sorting([1,2,3], [3,2,1,0]))
2.4570400714874268
>>> timeit(lambda: lensorting([1,2,3], [3,2,1,0]))
0.9596951007843018 # speed up
回答by radeklos
Needs ensurelibrary but you can compare list by:
需要确保库,但您可以通过以下方式比较列表:
ensure([1, 2]).contains_only([2, 1])
确保([1, 2]).contains_only([2, 1])
This will not raise assert exception. Documentation of thin is really thin so i would recommend to look at ensure's codes on github
这不会引发断言异常。Thin 的文档真的很薄,所以我建议在 github 上查看确保的代码
回答by Cory Klein
Given
给定的
l1 = [a,b]
l2 = [b,a]
assertCountEqual(l1, l2) # True
In Python >= 2.7, the above function was named:
在 Python >= 2.7 中,上述函数被命名为:
assertItemsEqual(l1, l2) # True
import unittest2
assertItemsEqual(l1, l2) # True
Via sixmodule(Any Python version)
通过six模块(任何 Python 版本)
import unittest
import six
class MyTest(unittest.TestCase):
def test(self):
six.assertCountEqual(self, self.l1, self.l2) # True

