[파이썬] - itertools 모듈 (순열과 조합 함수)

zsunny·2022년 7월 4일
0

[Python] 문법

목록 보기
11/18

🔎 itertools 모듈의 함수

  • from itertools import 함수명 으로 import한뒤 사용한다.
    1️⃣ combinations( )
    2️⃣ combinations_with_replacement( )
    3️⃣ product( )
    4️⃣ permutations( )

1️⃣ combinations( 리스트, r ) _ 리스트에서 r 개 뽑아 조합

from itertools import combinations

nums = [1, 2, 3]
for i in combinations(nums, 2):
	print(i)

-------------------------------------
# 출력결과
(1, 2)
(1, 3)
(2, 3)

2️⃣ combinations_with_replacement( 리스트, r ) _ 리스트에서 r 개 뽑아 중복조합

from itertools import combinations_with_replacement

nums = [1, 2, 3]
for i in combinations_with_replacement(nums, 2):
	print(i)

-----------------------------------------------------
# 출력결과
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)

3️⃣ permutaions( 리스트, r ) _ 리스트에서 r 개 뽑아 순열

from itertools import permutations

nums = [1, 2, 3]
for i in permutations(nums, 2):
	print(i)

------------------------------------
# 출력결과
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)

4️⃣ product( 리스트1, •••, repeat=1 ) _ 여러 리스트의 데카르트곱

from itertools import product

nums1 = [1, 2]
nums2 = ['a', 'b']
for i in product(nums1, nums2, repeat=1):
	print(i)

--------------------------------------------
# 출력결과
(1, 'a')
(1, 'b')
(2, 'a')
(2, 'b')
profile
매일 성장하는 예비 웹 개발자 🌱

0개의 댓글