Yineleyicilere giriş

Python Araç Kutusu

Hugo Bowne-Anderson

Data Scientist at DataCamp

for döngüsüyle yineleme

  • Bir listeyi for döngüsüyle yineleyebiliriz
employees = ['Nick', 'Lore', 'Hugo']

for employee in employees: print(employee)
Nick
Lore
Hugo
Python Araç Kutusu

for döngüsüyle yineleme

  • Bir dizeyi for döngüsüyle yineleyebiliriz
for letter in 'DataCamp':
    print(letter)
D
a
t
a
C
a
m
p
Python Araç Kutusu

for döngüsüyle yineleme

  • Bir range nesnesini for döngüsüyle yineleyebiliriz
for i in range(4):
    print(i)
0
1
2
3
Python Araç Kutusu

Yineleyiciler vs. yineleyebilirler

  • Yineleyebilir (iterable)
    • Örnekler: listeler, dizeler, sözlükler, dosya bağlantıları
    • iter() yöntemi olan nesne
    • Bir yineleyebilir üzerinde iter() bir yineleyici üretir
  • Yineleyici (iterator)
    • next() ile sıradaki değeri üretir
Python Araç Kutusu

Yineleyebilirlerde gezinme: 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 Araç Kutusu

* ile tek seferde yineleme

word = 'Data'
it = iter(word)

print(*it)
D a t a
print(*it)
  • Geçecek başka değer yok!
Python Araç Kutusu

Sözlükler üzerinde yineleme

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

for key, value in pythonistas.items(): print(key, value)
francis castro
hugo bowne-anderson
Python Araç Kutusu

Dosya bağlantıları üzerinde yineleme

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

print(next(it))
This is the first line.
print(next(it))
This is the second line.
Python Araç Kutusu

Hadi pratik yapalım!

Python Araç Kutusu

Preparing Video For Download...