
chain(*iterables)
arguments 로 복수 개의 iterable 객체를 받음.
이들 복수 개의 iterables 들을 합친 하나의 iteartor, chain 객체를 반환함.
해당 반환된 객체는 for 문으로 iterate가 가능함.
>>> for i in itertools.chain([0,1,2], [3,4], [[5,6],[7,8]],[9,10]):
... print(i)
...
0
1
2
3
4
[5, 6]
[7, 8]
9
10
>>>
cycle(iterable)
하나의 iterable을 반복적으로 iterate(순환)하는 iterator객체를 반환함.
아래의 에제는 무한히 출력이 이루어지므로 ctrl+c 로 interrupt를 보내야함.
>>> for i in itertools.cycle([0,1,2]):
... print(i)
...
0
1
2
0
1
2
생략
accumulate(iterable, func=None)
argument로 주어진 iterable 객체의 item들에 대한
accumulated sum을 구하거나,
binary function 에 현재의 item과 이전 결과값을 argument로 할당한 결과의 iterator 객체를 반환.
>>> def b_func(a,b):
... return a*b
...
>>> for i in itertools.accumulate([1,2,3,4],func=b_func):
... print(i)
...
1
2
6
24
>>>
>>> for i in itertools.accumulate([1,2,3,4]):
... print(i)
...
1
3
6
10
>>>
func파라메터에 binary function을 할당하지 않을 경우, 기본적으로 더하는 함수로서 accumulated sum을 구하게 됨.- 위의 예에서 두번째를 참조.
product
Catersian Product를 수행함.
https://dsaint31.tistory.com/654
[Math] Cartesian Product (or Descartes Product, Product Set)
Cartesian Product (or Descartes Product)공집합(empty set, null set)이 아닌 여러 sets를 이용하여 새로운 set을 만드는 연산. Cartesian product는operand인 여러 집합들의각 elements를 원소(component, element)로 하는 tuple을
dsaint31.tistory.com
repeat
같은 객체의 참조를 반복 (기본이 무한 반복 임을 기억할 것.)
mutable 객체 사용 시 주의
times 파라미터에 반복횟수를 argument로 지정시 유한횟수 반복.
from itertools import repeat
# signature
# itertools.repeat(object[, times])
# 무한히 10을 반복
for i in repeat(10):
print(i) # 10, 10, 10, ... (무한)
if i > 5:
break
# 10을 3번 반복
list(repeat(10, 3)) # [10, 10, 10]
# 문자열도 가능
list(repeat('hello', 4)) # ['hello', 'hello', 'hello', 'hello']
# map과 함께 사용 - 함수에 고정 인자 전달
list(map(pow, range(5), repeat(2))) # [0, 1, 4, 9, 16]
# pow(0, 2), pow(1, 2), pow(2, 2), ...
# zip과 함께 사용
list(zip(range(3), repeat('A'))) # [(0, 'A'), (1, 'A'), (2, 'A')]
count
range랑 비슷한 무한 정수 및 실수 생성기임.
기본이 무한 반복임을 기억할 것.
from itertools import count
# signature
# count(start=0, step=1)
counter = count()
next(counter) # 0
next(counter) # 1
next(counter) # 2
# 10부터 시작
for i in count(10):
print(i) # 10, 11, 12, ... (무한)
if i >= 13:
break
# 음수 step도 가능
for i in count(10, -1):
print(i) # 10, 9, 8, 7, ...
if i <= 7:
break
# 실수도 가능
for i in count(0.5, 0.5):
print(i) # 0.5, 1.0, 1.5, 2.0, ...
if i >= 2.5:
break
# enumerate 대신 사용
data = ['a', 'b', 'c']
list(zip(count(), data)) # [(0, 'a'), (1, 'b'), (2, 'c')]
# 무한 ID 생성기
id_gen = count(1)
next(id_gen) # 1
next(id_gen) # 2
Compress
data와 selector를 argument로 받아서 selector가 True인 요소만 선택.
filter()와 비슷하지만, 미리 계산된 경우라고 보면 됨.
itertools.compress(data, selectors)
다음의 예를 참고
from itertools import compress
data = ['A', 'B', 'C', 'D', 'E']
selectors = [1, 0, 1, 0, 1]
list(compress(data, selectors)) # ['A', 'C', 'E']
# ----------------------
data = [10, 20, 30, 40, 50]
# 30보다 큰 값만 선택
selectors = [x > 30 for x in data]
list(compress(data, selectors)) # [40, 50]
# ----------------------
data = ['a', 'b', 'c', 'd', 'e', 'f']
# 0, 2, 4번 인덱스만 선택
positions = [0, 2, 4]
selectors = [i in positions for i in range(len(data))]
list(compress(data, selectors)) # ['a', 'c', 'e']
# ----------------------
data = [1, 2, 3, 4, 5]
selectors = [1, 1] # 2개만
list(compress(data, selectors)) # [1, 2]
# selectors가 끝나면 중단됨'Python' 카테고리의 다른 글
| [Python] importlib.util.find_spec() (0) | 2024.03.08 |
|---|---|
| [Programming] glue code and (language) binding (0) | 2024.03.04 |
| [Python] Parameter 의 종류 - Slash and Asterisk for Function Parameters (1) | 2024.02.04 |
| [Python] mutable and immutable: Mutability (1) | 2024.02.03 |
| [Python] Module, Package and Library (+ Framework) (1) | 2024.02.03 |