이터레이터 소개

Python 도구 상자

Hugo Bowne-Anderson

Data Scientist at DataCamp

for 루프로 순회

  • for 루프로 리스트를 순회할 수 있습니다
employees = ['Nick', 'Lore', 'Hugo']

for employee in employees: print(employee)
Nick
Lore
Hugo
Python 도구 상자

for 루프로 순회

  • for 루프로 문자열을 순회할 수 있습니다
for letter in 'DataCamp':
    print(letter)
D
a
t
a
C
a
m
p
Python 도구 상자

for 루프로 순회

  • for 루프로 range 객체를 순회할 수 있습니다
for i in range(4):
    print(i)
0
1
2
3
Python 도구 상자

이터레이터 vs 이터러블

  • 이터러블
    • 예: 리스트, 문자열, 딕셔너리, 파일 연결
    • iter() 메서드가 있는 객체
    • 이터러블에 iter()를 적용하면 이터레이터 생성
  • 이터레이터
    • next()로 다음 값을 생성
Python 도구 상자

이터러블 순회: next()

word = 'Da'
it = iter(word)

next(it)
'D'
next(it)
'a'
next(it)
StopIteration                   Traceback (most recent call last)
<ipython-input-11-2cdb14c0d4d6> in <module>()
-> 1 next(it)
StopIteration:
Python 도구 상자

별표(*)로 한 번에 순회

word = 'Data'
it = iter(word)

print(*it)
D a t a
print(*it)
  • 더 이상 순회할 값이 없습니다!
Python 도구 상자

딕셔너리 순회

pythonistas = {'hugo': 'bowne-anderson', 'francis': 'castro'}

for key, value in pythonistas.items(): print(key, value)
francis castro
hugo bowne-anderson
Python 도구 상자

파일 연결 순회

file = open('file.txt')
it = iter(file)

print(next(it))
This is the first line.
print(next(it))
This is the second line.
Python 도구 상자

Passons à la pratique !

Python 도구 상자

Preparing Video For Download...