본문 바로가기

개발에 도움이 되는/Python

itertools (순열, 조합, 중복 순열, 중복 조합)

- 요약

 

순열 = permutations

조합 = combinations

중복 순열 = product

중복 조합 = combinations_with_replacement

 

 

 

# 모듈 선언

순열 : from itertools import permutations

조합 : from itertools import combinations

중복 순열 : from itertools import product

중복 조합 : from itertools import combinations_with_replacement

 

 

# 순열(permutations) 구현

permutations(순열을 구할 목록, 기준 개수)

 

ex)

 ex_list = ['a', 'b', 'c']

 ex_str = "abc"

 

 per_list = list(permutations(ex_list, 2)) -> [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

 ex_list에서 목록 2개를 뽑아서 순열 만들기. 

 ex_str로 해도 동일.

 순열 요소 반환 값은 tuple형이고 순열 목록은 list로 타입 변환해주면 편함.

 

 for p in permutations(ex_list, 2):

위 형식처럼 for문으로 요소 하나씩 꺼내기도 가능.

 

 

# 조합(combinations) 구현

combinations(조합을 구할 목록, 기준 개수)

 

ex)

 ex_list = ['a', 'b', 'c']

 ex_str = "abc"

 

 com_list = list(combinations(ex_list, 2)) -> [('a', 'b'), ('a', 'c'), ('b', 'c')]

 ex_list에서 목록 2개를 뽑아서 조합 만들기. 

 ex_str로 해도 동일.

 순열 요소 반환 값은 tuple형이고 순열 목록은 list로 타입 변환해주면 편함.

 

 for c in combinations(ex_list, 2):

 위 형식처럼 for문으로 요소 하나씩 꺼내기도 가능.

 

 

# 중복 순열 (product) 구현

product(중복 순열을 구할 목록, repeat = 기준 개수)

 

ex)

 ex_list = ['a', 'b', 'c']

 ex_list2 = [1, 2, 3]

 ex_str = "abc"

 

 pro_list = list(product(ex_list, repeat = 2)) -> [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]

 ex_list에서 목록 repeat에 설정한 개수만큼 뽑아서 중복 순열 만들기. 

 ex_str로 해도 동일.

 중복 순열 요소 반환 값은 tuple형이고 중복 순열 목록은 list로 타입 변환해주면 편함.

 

 for p in product(ex_list, repeat = 2):

 위 형식처럼 for문으로 요소 하나씩 꺼내기도 가능.

 

 pro_list = list(product(ex_list, ex_list2)) -> [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]

 위 형태의 꼴로 비교 대상 목록끼리의 순열도 구할 수 있음.

 

 

# 중복 조합(combinations_with_replacement) 구현

combinations_with_replacement(중복 조합을 구할 목록, 기준 개수)

 

ex)

 ex_list = ['a', 'b', 'c']

 ex_str = "abc"

 

 com_list = list(combinations_with_replacement(ex_list, 2)) -> [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]

 ex_list에서 목록 2개를 뽑아서 중복 조합 만들기. 

 ex_str로 해도 동일.

 중복 조합 요소 반환 값은 tuple형이고 중복 조합 목록은 list로 타입 변환해주면 편함.

 

 for c in combinations_with_replacement(ex_list, 2):

 위 형식처럼 for문으로 요소 하나씩 꺼내기도 가능.

반응형

'개발에 도움이 되는 > Python' 카테고리의 다른 글

heapq  (0) 2021.10.28
defaultdict  (0) 2021.10.04