IT

파이썬에서 두 목록에 동일한 요소가 포함되어 있다고 주장하는 방법은 무엇입니까?

lottoking 2020. 6. 28. 18:01
반응형

파이썬에서 두 목록에 동일한 요소가 포함되어 있다고 주장하는 방법은 무엇입니까? [복제]


테스트 사례를 작성할 때 종종 순서에 관계없이 두 목록에 동일한 요소가 포함되어 있다고 주장해야합니다.

목록을 세트로 변환 하여이 작업을 수행했습니다.

이 작업을 수행하는 더 간단한 방법이 있습니까?

편집 :

@MarkDickinson이 지적했듯이 TestCase.assertItemsEqual 만 사용할 수 있습니다 .

참고 TestCase.assertItemsEqualPython2.7의 새로운 기능입니다. 이전 버전의 Python을 사용하는 경우 Python 2.7의 새로운 기능의 백 포트 인 unittest2 를 사용할 수 있습니다 .


약간 더 빠른 구현 버전 (대부분의 커플 목록의 길이가 다른 것을 알고있는 경우) :

def checkEqual(L1, L2):
    return len(L1) == len(L2) and sorted(L1) == sorted(L2)

비교 :

>>> 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

파이썬 3.2로 unittest.TestCase.assertItemsEqual( 의사가 )로 대체되었습니다 unittest.TestCase.assertCountEqual( 문서 는 파이썬에서 읽을 수있는 당신이 찾고있는 정확하게 수행) 표준 라이브러리 문서 . 이 방법은 다소 오해의 소지가 있지만 원하는 것을 정확하게 수행합니다.

a와 b는 순서에 관계없이 동일한 번호의 동일한 요소를 갖습니다.

다음은 동일한 요소를 갖지만 순서가 다른 두 목록을 비교하는 간단한 예입니다.

  • assertCountEqual테스트를 사용 하면 성공합니다
  • 사용한 assertListEqual시험은 두 개의리스트의 순서 차이로 인해 실패

여기 작은 예제 스크립트가 있습니다.

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()

참고 : 비교하려는 목록의 요소가 정렬 가능한지 확인하십시오.


주어진

l1 = [a,b]
l2 = [b,a]

파이썬에서 > = 3.0

assertCountEqual(l1, l2) # True

In Python >= 2.7, the above function was named:

assertItemsEqual(l1, l2) # True

In Python < 2.7

import unittest2
assertItemsEqual(l1, l2) # True

Via six module (Any Python version)

import unittest
import six
class MyTest(unittest.TestCase):
    def test(self):
        six.assertCountEqual(self, self.l1, self.l2) # True

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


Needs ensure library but you can compare list by:

ensure([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

참고URL : https://stackoverflow.com/questions/12813633/how-to-assert-two-list-contain-the-same-elements-in-python

반응형