본문 바로가기
알고리즘

[파이썬] itertools 라이브러리

by 자바지기 2021. 9. 26.
반응형

itertools는 파이썬에서 반복되는 데이터를 처리하는 기능을 포함하는 라이브러리다.

 

itertools 중에서 유용하게 사용할 수 있는 클래스에 대하여 알아본다.

 

1.  permutations

iterable 객체에서 r개의 데이터를 뽑아 일렬로 나열하는 모든 경우를 계산한다.

사용 예:

from itertools import permutations

data = [ 1,2,3]
print(list(permutations(data,2)))  #[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

2. product

iterable 객체에서 중복을 허용하여 r개의 데이터를 뽑아 일렬로 나열하는 모든 경우를 계산한다.

사용 예:

from itertools import product

data = [1,2,3]
print(list(product(data, repeat=2))) #[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

3. combinations

iterable 객체에서 중복을 허용하지 않고 r개의 데이터를 뽑는 모든 경우를 계산한다.

from itertools import combinations

data = [1,2,3]
print(list(combinations(data,2))) #[(1, 2), (1, 3), (2, 3)]

4. combinations_with_replacement

iterable 객체에서 중복을 허용하여 r개의 데이터를 뽑는 모든 경우를 계산한다.

사용 예:

from itertools import combinations_with_replacement

data = [1,2,3]
print(list(combinations_with_replacement(data,2))) #[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
반응형

'알고리즘' 카테고리의 다른 글

[파이썬] asterisk( * )  (0) 2021.10.19
[파이썬] bisect 라이브러리  (0) 2021.09.26
[파이썬] heapq 라이브러리  (0) 2021.09.26
[파이썬] Counter 클래스 사용법  (0) 2021.09.08
정수에 대한 유클리드 호제법  (0) 2021.09.07

댓글