티스토리 뷰
-. 이터레이더(Iterator)
이터레이터 반복하다의 의미로서 for구문이 될수 있음
>>> for x in [1,2,3]: #리스트 순회
print(x)
1
2
3
>>> for x in (1,2,3): #튜플 순회
print(x)
1
2
3
>>> for x in {'one':1,'two':2}: #사전 순회
print(x)
two
one
>>> for x in '123': #문자열 순회
print(x)
1
2
3
for 구문은 이터레이터 안의 __next__() 메소드를 실행함
내부의 반복문을 관리해주는 역할
__next__()는 next()함수를 이용하여 실행할수도 있음
>>> s = 'abc'
>>> it = iter(s) #iter함수는 순회가능한 객체에서 이터레이터를 가져옴
>>> it
<str_iterator object at 0x0105ACF0>
>>> next(it)
'a'
>>> next(it)
'b'
>>> it.__next__() #next()가 불러오는 메소드를 직접 실행함
'c
>>> next(it) #이터레이더가 종료되어 호출할 값이 없음
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
next(it)
StopIteration
-. 제네레이터
이터레이터를 만드는 도구
>>> def reverse(data):
for index in range(len(data) -1, -1, -1):
yield data[index]
>>> for char in reverse('golf'):
print(char)
f
l
o
g
>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> sum(a)
55
>>> b = (i for i in range(11))
>>> sum(b)
55
a는 1에서 10까지를 저장할 메모리 공간필요
b처럼 만들면 메모리공간 필요없음
제네레이터는 메모리절약측면에서 유리함
'Python' 카테고리의 다른 글
Python, 참/거짓(bool) (0) | 2016.04.21 |
---|---|
Python, if문 (0) | 2016.04.21 |
Python, help (0) | 2016.04.21 |
Python, Pass (0) | 2016.04.21 |
Python, 재귀적 함수 호출 (0) | 2016.04.21 |
- Total
- Today
- Yesterday
- highlightthickness
- Private
- indicatoron
- ManyToOne
- disabledforeground
- apache
- 상수
- onetomany
- Composite Key
- 폼
- Java
- Excel
- activebackground
- checkbutton
- activeforeground
- Linux
- vba
- Module
- Python
- 파이썬
- tkinter
- command
- borderwidth
- highlightbackground
- tkinter command & bind [명령어묶기와 사건묶기] Python
- 리눅스
- FetchType
- JPA
- IdClass
- fetch join
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |