itertools - 조합형 이터레이터

박동규·2022년 5월 7일
0

python

목록 보기
3/3

itertools

효율적인 루핑을 위한 이터레이터를 만드는 함수

  • 무한 이터레이터, 가장 짧은 입력 시퀀스에서 종료되는 이터레이터, 조합형 이터레이터가 있다
  • 그 중 조합형 이터레이터는 카티샨 프로덕트, 순열, 조합을 만들어준다.
  • generator로, 생성시 변수에 저장해서 사용해야 한다.
from itertools import product, permutations, combinations, combinations_with_replacement

A = [1, 2, 3]
B = [4, 5]
C = [A, B]

product

product(literal, repeat = int)
  • literal의 모든 원소에 대해 cartisain product를 반환하는 generator
  • repeat:각 literal에 몇 개의 원소를 가지고 product 연산을 수행할 지 정하는 옵션으로 default는 1이다.
product_a = product(A, repeat = 3)
product_b = product(A, B)
product_c = product(*C)

for p in product_a:
    print(p, end =', ')
print('\n')

for p in product_b:
    print(p, end =', ')
print('\n')

for p in product_c:
    print(p, end =', ')

permutations

permutations(literal, int)
  • 순열을 만드는 generator로, 원소 개수를 지정하지 않으면 default: 1이다.
  • product 에서 자기 자신과의 조합을 제외한 literal를 만든다.
product_a = product(A, repeat = 2)
permutations_a = permutations(A, 2)
for p in product_a:
    print(p, end =', ')
print('\n')

for p in permutations_a:
    print(p, end = ', ')

combinations

combinations(literal, int)
  • 조합을 만드는 generator로, 원소 개수를 지정하지 않으면 default: 1이다.
  • permutations 각 원소간 순서를 고려한 literal를 만든다.
combinations_a = combinations(A, 2)
for c in combinations_a:
    print(c ,end = ', ')

print('\n')

combinations_with_replacement

combinations_with_replacement(literal, int)
  • 자기 자신과의 조합을 포함한 조합을 만드는 generator로, 원소 개수를 지정하지 않으면 default: 1이다.
  • product의 결과에 순서를 지키는 literal과 같다.
combinations_with_replacement_a = combinations_with_replacement(A, 2)
for c in combinations_with_replacement_a:
    print(c ,end = ', ')

print('\n')

docs

profile
근데 이제 불타는

0개의 댓글