[파이썬을 파이썬답게] itertools - 곱집합(Cartesian product)

이상해씨·2024년 2월 7일
0

Python

목록 보기
10/21

itertools

📌 itertools
파이썬 내장 모듈 중 하나로 반복가능한 데이터를 다루는데 유용한 도구를 제공. 반복문과 관련된 작업을 간단하게 만들어줌

  • 대표적인 함수
    • itertools.product: 여러 반복 가능한 객체에 대한 곱집합(cartesian product)을 생성
    • itertools.permutations: 주어진 길이의 순열을 생성
    • itertools.combinations: 주어진 길이의 조합을 생성
    • itertools.cycle: 주어진 iterable을 무한히 반복
    • itertools.chain: 여러 iterable을 하나로 연결
    • itertools.count: 무한 등차수열을 생성

곱집합(Cartesian product)

  • 두 집합 간의 모든 가능한 조합을 나타내는 집합
  • for문 사용하여 구하기
iterable1 = 'abcd'
iterable2 = 'xy'
iterable3 = '1234'

for value1 in iterable1:
    for value2 in iterable2:
        for value3 in iterable3:
            print(value1, value2, value3)
  • itertools.product를 사용하기
import itertools

iterable1 = 'abcd'
iterable2 = 'xy'
iterable3 = '1234'
print(list(itertools.product(iterable1, iterable2, iterable3)))

참고

profile
공부에는 끝이 없다

0개의 댓글