본문 바로가기
Programming/Python

[오늘의 짬지식] 리스트 모든 경우의 수 : from itertools

by 남르미누 2021. 6. 12.

파이썬 python 에서 리스트 값들의 모든 조합 경우의 구하기

 

*** 하나의 리스트에서 모든 경우의 수, 조합 수 구하기

: from itertools import permutations

: from itertools import combinations

from itertools import permutations, combinations

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

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

list(permutations(items, 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)]

list(combinations(items, 2))
# [(1, 2),(1, 3),(1, 4),(1, 5),(2, 3),(2, 4),(2, 5),(3, 4),(3, 5),(4, 5)]

 

*** 두개 이상의 리스트에서 모든 경우의 수, 조합 수 구하기

: from itertools import product

from itertools import product

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

items = [['a','b','c'],[1,2,3],['!','@','$']]

list(product(*items))
# [('a', 1, '!'),('a', 1, '@'),('a', 1, '$'),('a', 2, '!'),('a', 2, '@'),('a', 2, '$'),('a', 3, '!'),('a', 3, '@'),('a', 3, '$'),('b', 1, '!'),('b', 1, '@'),('b', 1, '$'),('b', 2, '!'),('b', 2, '@'),('b', 2, '$'),('b', 3, '!'),('b', 3, '@'),('b', 3, '$'),('c', 1, '!'),('c', 1, '@'),('c', 1, '$'),('c', 2, '!'),('c', 2, '@'),('c', 2, '$'),('c', 3, '!'),('c', 3, '@'),('c', 3, '$')]

댓글