Python 의 itertools

SUSU·2023년 8월 26일
0

'itertools'반복자(iterator)를 다루는 유용한 도구들을 제공하는 모듈이다.
for 문과 함께 사용되고, 다음 요소를 가져오는 'next()' 함수와 같이 쓰이는 경우도 많다. 반복자 객체 안에서 값을 하나씩 순서대로 꺼내서 처리할 때 유용함

아래는 자주 사용하는 주요 함수와 그 예제들

1. itertools.count(start=0, step=1)

지정된 시작값(start)과 스텝(step)으로 무한한 숫자 시퀀스를 생성합니다.

from itertools import count

for num in count(1,2):
	if  num > 10:
    	break
    print(num)  #1,3,5,7,9 를 출력

2.itertools.cycle(iterable)

주어진 iterable 을 무한 반복한다

from itertools import cycle

colors = cycle(['red','orange','yellow']) #이런 값의 리스트를 넣으면
for i in range(6):
	print(next(colors))  #next를 사용하지 않으면 그냥 주소값이 출력됨
    # red,orange,yellow,red,orange,yellow 이렇게 리스트 6번 반복됨

3.itertools.permutations(iterable, r)

주어진 iterable 에서 길이가 r인 순열을 생성
※튜플로 생성됨. 순열이기 때문에 순서가 중요하며, 같은 원소를 포함하더라도 순서가 다르면 다른 순열로 간주된다.

from itertools import permutations

perms = permutations('ABC', 2)
for i in perms:
	print(i)
    # ('A', 'B'), ('A', 'C'), 
    # ('B', 'A'), ('B', 'C'), 
   # ('C', 'A'), ('C', 'B') 출력

4. itertools.combinations(iterable,r)

주어진 iterable 에서 길이가 r인 조합을 생성
※튜플로 생성됨. 조합이기 때문에 순서는 중요하지 않으며, 같은 원소를 포함하면 순서가 다르더라도 같은 조합으로 간주된다.

from itertools import combinations

combos = combinations('ABC', 2)
for i in combos:
	print(i)
    # ('A', 'B'), ('A', 'C'), ('B', 'C') 출력

5. itertools.product(iterable1, iterable2,...,repeat=n)

주어진 iterable 에서 요소를 n번 반복하여 조합을 생성.
repeat는 생략이 가능하며 기본값은 1
※permutations(),combinations()와 달리 요소의 중복 사용이 가능하다

import itertools 

products = itertools.product("AB", repeat=2)
for i in products:
	print(i)
    #('A', 'A'),('A', 'B'),('A', 'C')
    #('B', 'A'),('B', 'B'),('B', 'C')
    #('C', 'A'),('C', 'B'),('C', 'C')출력

6. itertools.chain(iterable1, iterable2,...)

여러 iterable 을 하나로 연결한다

list1 =[a,b,c]
list2 =[d,e,f]
combind  = chain(list1, list2)
for i in combined:
	print(i)

#chain이 필요한 경우도 있겠지만 fot문 없이 사용 할수 없고 
for item in list1+list2:
    print(item)
#로도 같은 값이 출력 되기 때문에 사용 빈도는 낮은편이라고 생각됨
profile
기록용

0개의 댓글