Python

파이썬(Python) 리스트 모든 조합 구하기

nineDeveloper 2020. 12. 25.
728x90

하나의 리스트에서 모든 조합을 구하기

array = [1, 2, 3, 4, 5]

from itertools import permutations
list(permutations(array, 2))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)]

from itertools import combinations
list(combinations(array, 2))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

하나의 리스트에서 모든 자리수에 대한 조합을 구해서 연결한 하나의 리스트 만들기

array = [1, 2, 3, 4, 5]

from itertools import chain, combinations
chain.from_iterable(combinations(array, r) for r in range(1, len(array) + 1))

# 더 빠른 방법
chain.from_iterable(combinations(array, r) for r in range(1, len(array + 1)))

# [(1,), (2,), (3,), (4,), (5,), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5), (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5), (1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5), (1, 2, 3, 4, 5)]

두개 이상의 리스트의 모든 조합 구하기

from itertools import product
list(product(*array))
# [('a', 1, '!'), ('a', 1, '@'), ('a', 1, '#'), ('a', 2, '!'), ('a', 2, '@'), ('a', 2, '#'), ('a', 3, '!'), ('a', 3, '@'), ('a', 3, '#'), ('a', 4, '!'), ('a', 4, '@'), ('a', 4, '#'), ('a', 5, '!'), ('a', 5, '@'), ('a', 5, '#'), ('b', 1, '!'), ('b', 1, '@'), ('b', 1, '#'), ('b', 2, '!'), ('b', 2, '@'), ('b', 2, '#'), ('b', 3, '!'), ('b', 3, '@'), ('b', 3, '#'), ('b', 4, '!'), ('b', 4, '@'), ('b', 4, '#'), ('b', 5, '!'), ('b', 5, '@'), ('b', 5, '#'), ('c', 1, '!'), ('c', 1, '@'), ('c', 1, '#'), ('c', 2, '!'), ('c', 2, '@'), ('c', 2, '#'), ('c', 3, '!'), ('c', 3, '@'), ('c', 3, '#'), ('c', 4, '!'), ('c', 4, '@'), ('c', 4, '#'), ('c', 5, '!'), ('c', 5, '@'), ('c', 5, '#')]

출처

https://qastack.kr/programming/464864/how-to-get-all-possible-combinations-of-a-list-s-elements
https://docs.python.org/2/library/itertools.html#recipes

728x90

댓글

💲 추천 글