프로그래밍 언어/Python
[Python] 파이썬 리스트 모든 조합 구하기
claire
2022. 4. 22. 14:21
파이썬에서 리스트에 있는 값들의 모든 조합을 구하기 위해서는 여러 방법이 있다. 파이썬 기본 라이브러리인 itertools를 사용하면 쉽게 구할 수 있다.
from itertools import product
from itertools import permutations
from itertools import combinations
- 하나의 리스트에서 모든 조합을 계산해야 한다면 permutations, combinations를 사용.
- 두개 이상의 리스트에서 모든 조합을 계산해야 한다면 product를 사용.
//순열 - 순서가 있음
items=['1','2','3','4','5']
from itertools import permutations
list(permutations(items,2))
//조합 - 순서 없음
from itertools import combinations
list(combinations(itmes,2))
//두개 이상의 리스트의 모든 조합 구하기
from itertools import product
items = [['a', 'b', 'c,'], ['1', '2', '3', '4'], ['!', '@', '#']]
list(product(*items))
# [('a', '1', '!'), ('a', '1', '@'), ('a', '1', '#'), ('a', '2', '!'),
#('a', '2', '@'), ('a', '2', '#'), ('a', '3', '!'), ('a', '3', '@'),
#('a', '3', '#'), ('a', '4', '!'), ('a', '4', '@'), ('a', '4', '#')....