Python의 itertools
모듈은 반복 가능한(iterable) 데이터의 다양한 조합과 순열을 생성하는 유용한 도구를 제공한다. 이 글에서는 itertools
모듈의 product
, permutations
, combinations
함수에 대해 살펴보겠다.
product()
product()
함수는 두 개 이상의 반복 가능한 객체의 데카르트 곱을 구한다. 이는 중첩된 반복문을 사용하는 것과 유사하다.
from itertools import product
list1 = [1, 2]
list2 = ['a', 'b']
product_result = list(product(list1, list2))
print(product_result)
# 출력: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
위의 예제에서는 리스트 [1, 2]
와 ['a', 'b']
의 데카르트 곱을 구하여 모든 가능한 조합을 생성하였다.
permutations()
permutations()
함수는 주어진 반복 가능한 객체에서 가능한 모든 순열을 생성한다. 순열은 원소의 순서를 고려하여 선택하는 경우를 의미한다. 선택할 원소의 개수를 지정할 수 있으며, 기본값은 원본 리스트의 길이이다.
from itertools import permutations
my_list = [1, 2, 3]
permutations_result = list(permutations(my_list))
print(permutations_result)
# 출력: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
위의 예제에서는 리스트 [1, 2, 3]
의 모든 순열을 생성하였다. 선택할 원소의 개수를 지정할 수도 있다.
permutations_result = list(permutations(my_list, 2))
print(permutations_result)
# 출력: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
combinations()
combinations()
함수는 주어진 반복 가능한 객체에서 가능한 모든 조합을 생성한다. 조합은 원소의 순서를 고려하지 않고 선택하는 경우를 의미한다.
from itertools import combinations
my_list = [1, 2, 3]
combinations_result = list(combinations(my_list, 2))
print(combinations_result)
# 출력: [(1, 2), (1, 3), (2, 3)]
위의 예제에서는 리스트 [1, 2, 3]
에서 길이가 2인 모든 조합을 생성하였다.
combinations_with_replacement()
combinations_with_replacement()
함수는 주어진 반복 가능한 객체에서 가능한 모든 조합을 생성하되, 동일한 원소를 여러 번 선택할 수 있다.
from itertools import combinations_with_replacement
my_list = [1, 2, 3]
combinations_with_replacement_result = list(combinations_with_replacement(my_list, 2))
print(combinations_with_replacement_result)
# 출력: [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
위의 예제에서는 리스트 [1, 2, 3]
에서 길이가 2인, 동일한 원소를 포함할 수 있는 모든 조합을 생성하였다.