如何在Python中断言两个列表包含相同的元素? [英] How to assert two list contain the same elements in Python?

查看:31
本文介绍了如何在Python中断言两个列表包含相同的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写测试用例时,我经常需要断言两个列表包含相同的元素,而不考虑它们的顺序.

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?

编辑:

正如@MarkDickinson 指出的,我可以只使用 TestCase.assertItemsEqual.

As @MarkDickinson pointed out, I can just use TestCase.assertItemsEqual.

请注意,TestCase.assertItemsEqual 是 Python2.7 中的新内容.如果您使用的是旧版本的 Python,您可以使用 unittest2 - 一个向后移植的新功能Python 2.7.

Notes that TestCase.assertItemsEqual is 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.

推荐答案

自 Python 3.2 unittest.TestCase.assertItemsEqual(doc) 已替换为 unittest.TestCase.assertCountEqual(doc) 完全符合您的要求,正如您可以从 python 标准库文档.该方法的名称有些误导,但它完全符合您的要求.

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.

a 和 b 具有相同数量的相同元素,无论它们的顺序如何

a and b have the same elements in the same number, regardless of their order

这是一个简单的例子,它比较了两个元素相同但顺序不同的列表.

Here a simple example which compares two lists having the same elements but in a different order.

  • 使用 assertCountEqual 测试会成功
  • 使用assertListEqual测试会因为两个列表的顺序不同而失败
  • using assertCountEqual the test will succeed
  • using assertListEqual the test will fail due to the order difference of the two lists

这里有一个小示例脚本.

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.

这篇关于如何在Python中断言两个列表包含相同的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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