python 조합, 순열 (combinations, permutations), 프로덕트(product)

2022. 9. 30. 12:09Programming

728x90

1. 패키지: itertools

from itertools import combinations
from itertools import permutations
from itertools import product

2. 차이

- 대상 리스트가 1개일 경우: combinations, permutations를 사용

- 대상 리스트가 1개보다 많을 경우: product

 

3. 예제

- combinations(조합, 순서고려X), permutations(순열, 순서고려)

items = [1, 2, 3, 4, 5]
print(list(combinations(items, 2)))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

print(list(permutations(items, 2)))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)]
728x90

- product(각 list 조합)

items_1 = [1, 2, 3]
items_2 = ['a', 'b']
items_3 = ['!', '@']
print(list(product(*[items_1, items_2, items_3])))
# [(1, 'a', '!'), (1, 'a', '@'), (1, 'b', '!'), (1, 'b', '@'), (2, 'a', '!'), (2, 'a', '@'), (2, 'b', '!'), (2, 'b', '@'), (3, 'a', '!'), (3, 'a', '@'), (3, 'b', '!'), (3, 'b', '@')]

 

 

반응형