1. iterable
- for 문에 사용 가능
- 동시에 여러개 값을 처리한는거같지만 내부적으로 1씩 뽑아서 처리
- iterable : iterator 이 되 수 있음
- 대부분의 컨테이너는 iterable :list, dictionary, tuple..
#a의 값은 1개, 원소 3개
a= [1,2,3,] #여러 값을 한번에 할당
#list는 iterable
dir(a) # _iter__ -> iterable -> iterator 될 수 있음
list('abc') # instance 문자열을 쪼갬
==> ['a', 'b', 'c']
['a', 'b', 'c'] #lietral
==> ['a', 'b', 'c']
2. iterable 종류
(1) set
a= {1,2,3}
b= iter(a)
b
==> <set_iterator at 0x7ffcb2d31f50>
(2) dictionary
c= {1:1,2:2}
d= iter(e)
d
==> <dict_keyiterator at 0x1d6f8201458>
(3) list
e= [1,2,3]
f= iter(e)
f
==> <list_iterator at 0x7ffcb2d03850>
(4) tuple
g =(1,2,3,)
h= iter(c)
h
==> <tuple_iterator at 0x7ffcb2cecd10>
(5) range
x= iter(range(10))
x
==> <range_iterator at 0x1d6f88de450>
3. iter : 아주 큰 데이터가 있을때 전체를 메모리를 올리지 않고 특정한것만 메모리 올라감 (데이터 처리 매우 유용)
b= iter(a) #iterator가 하나씩 처리
4. next
- iterator에서 컨테이너 내부의 원소를 차례대로 하나씩 추출
- iterator 가 되면 next 쓸 수 있음
next(b)
==> 1
next(b)
==>2
next(b)
==> 3
next(b) #더 이상 없는 경우 StopIteration
==>StopIteration
list(b) #남은 값 확인: 없음
==> []
b[0] #indexing 불가
==> TypeError: 'list_iterator' object is not subscriptable
5. itertools
- 빠르고 메모리를 효율적으로 사용함
- iterator에 사용할 수있는 다양한 function 을 제공해서 더욱 복잡한 iterator 만들어주는 모듈
from itertools import count, cycle, accumulate
(1) count : Inf 까지 계속해서 실행 횟수
a=count()
next(a)
next(a)
dir(a)
(2) cycle
- 순환형 iterator
- 이전의 iterator는 한 번 돌면 StopIteration 에러와 함께 멈추지만 순황형을 다시 처음으로 돌아감
cycle #iterable series -> __next__ (한개씩 추출)
==> itertools.cycle
d=cycle('abc') #itertools.cycle
dir(d)
next(d) # 1번
next(d) # 1번
next(d) # 3번
next(d) # 1번 재순환시작
(3) accumulate : 값들의 누계 합
e = accumulate([1,2,3], lambda x,y:x*x+y)
e
==> <itertools.accumulate at 0x7f92fdd480a0>
next(e)
==> 1
next(e)
==> 3
next(e)
==> 12
5. 무한 순환 Iterator
def cycle():
while True: #무한 루프
yield 1
x= cycle()
next(x)
==> 1
next(x)
==>1