[python] itertools.combinations

n개의 항목 중에서 k 항목을 꺼내는 모든 가능한 경우를 구하는 방법은?
간단하진 않은 거 같은데, 파이썬에서는 이를 위한 함수를 제공한다.
itertools라는 모듈안에 combinations이라는 함수가 이 역할을 한다.

다음 코드는 4개의 항목으로 구성된 list인 a_list에서 3개의 항목을 꺼내는 모든 경우를 출력한다.

############################
#!/usr/bin/env python

import itertools

a_list = ["a", "b", "c", "d"]

for sub_tuple in itertools.combinations(a_list, 3):
    print(sub_tuple)

# vim: sw=4 ts=4 autoindent

################################
출력 결과는 다음과 같다.

('a', 'b', 'c')
('a', 'b', 'd')
('a', 'c', 'd')
('b', 'c', 'd')

################################

참고자료: 9.7. itertools — Functions creating iterators for efficient looping

댓글

이 블로그의 인기 게시물

utf-8과 utf8