반응형
python 에서 리스트를 구성하는 원소간의 조합을 만들고 싶을 때 여러 방법이 있지만 itertools.product 를 사용하는 방법이 있다.
itertools.product 설명 및 예시
itertools을 이용하면 두개 이상의 리스트에 관하여 리스트 간의 cartesian product를 구해준다. 예시를 보면서 이해하는 것이 빠를것 같다.
import itertools
A = [1,2,4]
list(itertools.product(A, repeat=2))
>>>> [(1, 1), (1, 2), (1, 4), (2, 1), (2, 2), (2, 4), (4, 1), (4, 2), (4, 4)]
A = [0,1]
list(itertools,prodcut(A, repeat=3))
>>>> [(0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)]
A = [[0,1,2], [3, 4]]
list(itertools.product(*A))
>>>> [(0, 3), (0, 4), (1, 3), (1, 4), (2, 3), (2, 4)]
A = [0,1,2]
B = [3,4]
list(itergools.product(A,B)) #위의 결과와 동일반응형
댓글