728x90
조합
list에서 조합을 구할 때 사용
- permutations
- combinations
- product
Permutations, Combinations
하나의 list에서 조합을 구하는 것
- (1, 2) (2, 1) 이 있을 때
- permutations는 다르다고 판단하여 두개를 같이 반환하고
- combinations는 같다고 판단하여 (1, 2) 만 반환함
from itertools import product
from itertools import permutations
a = [1,2,3,4,5]
# (1, 2), (2, 1)는 다른 것으로 치부
print(list(permutations(a, 2)))
print(list(permutations(a, 3)))
print('-----------------------------------------------------------------')
print(list(combinations(a, 2)))
print(list(combinations(a, 3)))
[(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)]
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 2), (1, 3, 4), (1, 3, 5), (1, 4, 2), (1, 4, 3), (1, 4, 5), (1, 5, 2), (1, 5, 3), (1, 5, 4), (2, 1, 3), (2, 1, 4), (2, 1, 5), (2, 3, 1), (2, 3, 4), (2, 3, 5), (2, 4, 1), (2, 4, 3), (2, 4, 5), (2, 5, 1), (2, 5, 3), (2, 5, 4), (3, 1, 2), (3, 1, 4), (3, 1, 5), (3, 2, 1), (3, 2, 4), (3, 2, 5), (3, 4, 1), (3, 4, 2), (3, 4, 5), (3, 5, 1), (3, 5, 2), (3, 5, 4), (4, 1, 2), (4, 1, 3), (4, 1, 5), (4, 2, 1), (4, 2, 3), (4, 2, 5), (4, 3, 1), (4, 3, 2), (4, 3, 5), (4, 5, 1), (4, 5, 2), (4, 5, 3), (5, 1, 2), (5, 1, 3), (5, 1, 4), (5, 2, 1), (5, 2, 3), (5, 2, 4), (5, 3, 1), (5, 3, 2), (5, 3, 4), (5, 4, 1), (5, 4, 2), (5, 4, 3)]
-----------------------------------------------------------------
[(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)]
Product
2개의 list에서 조합을 구하는 것
from itertools import combinations
a = [1,2,3,4]
b = [5,6,7,8,9]
print(list(product(a, b)))
[(1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9)]
728x90
'Python > 이론, 기초' 카테고리의 다른 글
[Python] 한줄로 for+ if 문 사용하기 (0) | 2023.02.09 |
---|---|
[Python] 코드 실행 시간 측정 (0) | 2022.10.07 |
[Python] 진수 변환 (1) | 2022.09.28 |
[Python] heapq 라이브러리 사용하기 (0) | 2022.09.05 |
[Python] log 사용하기 (0) | 2022.08.29 |