iterate : μννλ€, λ°λ³΅νλ€
λ°λ³΅μ μΌλ‘ νλνλ κΊΌλ΄μ΄ μ²λ¦¬ κ°λ₯ν 컬λ μ μ΄λ sequence λ€μ μ΄ν°λ μ΄ν° κ°μ²΄λΌκ³ νλ€.
μ΄ν°λ μ΄ν°λ next()ν¨μλ₯Ό ꡬνν κ°μ²΄λ‘, next()ν¨μλ μν κ°λ₯ν
κ°μ²΄μ λ€μ μμλ₯Ό λ°ννλ€.
νμ΄μ¬μ μ΄ν°λ μ΄ν°ν
list, dict, set, bytes, tuple, range,
π μ΄ν°λ μ΄ν° νμΈν΄λ³΄κΈ°
try:
l = [1,2,3,4]
iterator = iter(l)
except typeError:
print('리μ€νΈλ μ΄ν°λ μ΄ν° κ°μ²΄κ° μλλλ€')
else:
print('리μ€νΈλ μ΄ν°λ μ΄ν° κ°μ²΄μ
λλ€.')
#result : 리μ€νΈλ μ΄ν°λ μ΄ν° κ°μ²΄μ
λλ€.
μμμ next() ν¨μλ‘ κ΅¬νν κ°μ²΄λΌλλ°, next() ν¨μκ° λκΉ?
μλ κ°λ¨ν μμ λ‘ μ΄ν΄λ³΄μ.
l = [2,4,5,7]
print(type(l)) #<class 'list'>
l_iter = iter(l)
print(type(l_iter)) #<class 'list_iterator'>
print(next(l_iter)) #2
print(next(l_iter)) #4
print(l_iter.__next__()) #5
next() ν¨μ νΉμ _ _ next__ λ₯Ό μ΄μ©ν΄μ iterator κ°μ²΄μ λ€μ μμ(element)λ₯Ό μ»μ μ μλ€
(μΈλλ° λκ°λ€,, μΈλλ° λκ° μ λ ₯νλ©΄ μκΎΈ κΈ°μΈμλΌμ νμΉΈ λμ΄μ μΌλ€,,π
)
μ°Έκ³ : https://www.youtube.com/watch?v=kpSChXZMKOc
for- in λ¬Έμμ μ¬μ©λλ rangeν¨μλ rangeν κ°μ²΄λ₯Ό λ§λ λ€
range(5)
range(0,5)
type(range(5))
r_iter = iter(range(5))
print(next(r_iter)) #0
π μμ νκΈ°
λ€μμ κ°λ¨ν ν€λ₯Ό μΆλ ₯νλ λμ λ리μ λν for λ¬Έμ whileλ¬ΈμΌλ‘ ꡬννκΈ°
D = {'a':1, 'b':2, 'c':3} for key in D.keys(): print(key)
D_keys = iter(D.keys())
while True:
try:
print(next(D_keys))
except StopIteration as e:
break