How to efficiently compare two unordered lists (not sets) in Python?

前端 未结 10 1113
刺人心
刺人心 2020-11-22 15:00
a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]

a & b should be considered equal, because they have exactly the same elements, only in different

10条回答
  •  渐次进展
    2020-11-22 15:42

    If you have to do this in tests: https://docs.python.org/3.5/library/unittest.html#unittest.TestCase.assertCountEqual

    assertCountEqual(first, second, msg=None)

    Test that sequence first contains the same elements as second, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated.

    Duplicate elements are not ignored when comparing first and second. It verifies whether each element has the same count in both sequences. Equivalent to: assertEqual(Counter(list(first)), Counter(list(second))) but works with sequences of unhashable objects as well.

    New in version 3.2.

    or in 2.7: https://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertItemsEqual

    Outside of tests I would recommend the Counter method.

提交回复
热议问题