itertools.combinations 모듈 파이썬

yun·2024년 7월 18일
post-thumbnail

itertools.combinations란?

itertools.combinations는 Python의 표준 라이브러리인 itertools 모듈에 포함된 함수 중 하나로, 주어진 iterable에서 원소의 순서를 고려하지 않고 지정된 길이의 조합을 생성한다.

사용법

  • 모듈 불러오기
from itertools import combinations
  • 주요 특징
    순서 고려하지 않음: 조합을 생성할 때 원소의 순서는 고려되지 않는다.
    예를 들어, (A, B)와 (B, A)는 동일한 조합으로 간주된다.
    생성된 조합에는 중복이 없다.

  • 리스트에서 조합 생성

import itertools

data = [1, 2, 3, 4]
combs = itertools.combinations(data, 2)

for comb in combs:
    print(comb)
출력:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
  • 문자열에서 조합 생성
import itertools

data = 'ABCD'
combs = itertools.combinations(data, 2)

for comb in combs:
    print(''.join(comb))

출력:

코드 복사
AB
AC
AD
BC
BD
CD
  • 조합을 리스트로 변환
import itertools

data = [1, 2, 3, 4]
combs = list(itertools.combinations(data, 3))
print(combs)

출력:
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

💡

오늘 프로그래머스 삼총사 문제를 풀기위해 검색해보다 알게 된 combinations 함수. 편리한 기능인 것 같아 정리해 보았다.

0개의 댓글