본문 바로가기

Language/Python

Python~combinations()함수 사용법

반응형

combinations()함수란

combinations(iterable, r)

입력받은 iterable을 r의 길이만큼 조합하여 리턴하는 함수입니다.

combinations()함수의 사용 예

사용에 앞서 itertools로 부터combinations함수를 임포트 해야 합니다.

from itertools import combinations

for i in combinations([0,1,2,3], 3):
    print(i)
# 결과 : (0, 1, 2) (0, 1, 3) (0, 2, 3) (1, 2, 3)

for i in combinations('abcd', 3):
    print(i)
# 결과 : ('a', 'b', 'c') ('a', 'b', 'd') ('a', 'c', 'd') ('b', 'c', 'd')

for i in combinations(range(4), 3):
    print(i)
# 결과 : (0, 1, 2) (0, 1, 3) (0, 2, 3) (1, 2, 3)

*참고 python 공식Document
https://docs.python.org/3/library/itertools.html#itertools.combinations

 

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...

docs.python.org

 

반응형

'Language > Python' 카테고리의 다른 글

Python~zip()함수 사용법  (0) 2023.04.14
Python~삼항연산자  (0) 2023.03.22
Python~제곱, 제곱근  (0) 2023.02.14
Python~문자열 나누기 String split(), list 변환, Indexing & Slicing  (0) 2022.05.31