728x90
반응형
아래는 Python의 itertools 모듈에서 제공하는 주요 함수들과 그 설명 및 예제들입니다. itertools는 반복(iterable) 작업을 편리하게 해주는 강력한 도구들을 제공합니다.
1. itertools.product
itertools.product는 데카르트 곱(Cartesian Product)을 생성합니다. 여러 반복 가능한 객체에서 가능한 모든 조합을 생성합니다.
문법
itertools.product(*iterables, repeat=1)
예제
from itertools import product
# 두 리스트의 데카르트 곱
for p in product([1, 2], ['a', 'b']):
print(p)
# 출력: (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')
# 하나의 리스트를 2번 반복한 조합
for p in product([1, 2], repeat=2):
print(p)
# 출력: (1, 1), (1, 2), (2, 1), (2, 2)
2. itertools.permutations
itertools.permutations는 순열을 생성합니다. 주어진 iterable에서 요소들의 순서를 고려한 조합을 반환합니다.
문법
itertools.permutations(iterable, r=None)
- iterable: 순열을 생성할 대상.
- r: 순열의 길이. 기본값은 iterable 전체 길이.
예제
from itertools import permutations
# 길이 3의 리스트의 순열
for p in permutations([1, 2, 3]):
print(p)
# 출력: (1, 2, 3), (1, 3, 2), (2, 1, 3), ...
# 길이 2의 순열
for p in permutations(['A', 'B', 'C'], 2):
print(p)
# 출력: ('A', 'B'), ('A', 'C'), ('B', 'A'), ...
3. itertools.combinations
itertools.combinations는 조합을 생성합니다. 주어진 iterable에서 순서를 고려하지 않은 조합을 반환합니다.
문법
itertools.combinations(iterable, r)
- iterable: 조합을 생성할 대상.
- r: 조합의 길이.
예제
from itertools import combinations
# 길이 3의 리스트에서 2개의 조합
for c in combinations([1, 2, 3], 2):
print(c)
# 출력: (1, 2), (1, 3), (2, 3)
# 문자열의 조합
for c in combinations('ABC', 2):
print(c)
# 출력: ('A', 'B'), ('A', 'C'), ('B', 'C')
4. itertools.combinations_with_replacement
itertools.combinations_with_replacement는 중복 허용 조합을 생성합니다. 같은 요소를 여러 번 선택할 수 있습니다.
문법
itertools.combinations_with_replacement(iterable, r)
예제
from itertools import combinations_with_replacement
# 중복 허용 조합
for c in combinations_with_replacement([1, 2, 3], 2):
print(c)
# 출력: (1, 1), (1, 2), (1, 3), (2, 2), ...
5. itertools.accumulate
itertools.accumulate는 요소를 누적 계산합니다. 기본적으로 합계를 누적 계산하며, 다른 이진 함수도 사용할 수 있습니다.
문법
itertools.accumulate(iterable, func=operator.add)
예제
from itertools import accumulate
import operator
# 누적 합
print(list(accumulate([1, 2, 3, 4])))
# 출력: [1, 3, 6, 10]
# 누적 곱
print(list(accumulate([1, 2, 3, 4], operator.mul)))
# 출력: [1, 2, 6, 24]
6. itertools.chain
itertools.chain은 여러 iterable 객체를 하나로 연결합니다.
문법
itertools.chain(*iterables)
예제
from itertools import chain
# 여러 리스트 연결
print(list(chain([1, 2], ['a', 'b'], [3, 4])))
# 출력: [1, 2, 'a', 'b', 3, 4]
7. itertools.islice
itertools.islice는 iterable 객체의 일부를 슬라이싱합니다.
문법
itertools.islice(iterable, start, stop, step=1)
예제
from itertools import islice
# 리스트의 일부 슬라이싱
print(list(islice(range(10), 2, 8, 2)))
# 출력: [2, 4, 6]
8. itertools.cycle
itertools.cycle은 iterable 객체를 무한히 반복합니다.
문법
itertools.cycle(iterable)
예제
from itertools import cycle
# 무한 반복
counter = cycle([1, 2, 3])
for _ in range(6):
print(next(counter))
# 출력: 1, 2, 3, 1, 2, 3
9. itertools.repeat
itertools.repeat은 특정 값을 지정된 횟수만큼 반복합니다.
문법
itertools.repeat(object, times=None)
예제
from itertools import repeat
# 값 반복
print(list(repeat(10, 4)))
# 출력: [10, 10, 10, 10]
10. itertools.groupby
itertools.groupby는 데이터를 그룹화하여 반복자를 반환합니다. 연속된 값만 그룹화합니다.
문법
itertools.groupby(iterable, key=None)
예제
from itertools import groupby
# 그룹화 예제
data = [1, 1, 2, 2, 3, 3, 3]
for key, group in groupby(data):
print(key, list(group))
# 출력:
# 1 [1, 1]
# 2 [2, 2]
# 3 [3, 3]
'Category > Python' 카테고리의 다른 글
| Python에서 heapq로 최대힙, 최소힙 구현하기 (0) | 2024.11.18 |
|---|---|
| 파이썬 정렬 함수 sort()와 sorted() 차이점 (0) | 2024.11.18 |
| Python에서 __init__과 self의 역할 (0) | 2024.11.17 |
| zip 함수란? (0) | 2024.11.16 |
| SQLAlchemy란? (2) | 2024.09.18 |