Introduction to iterators

Python Toolbox

Hugo Bowne-Anderson

Data Scientist at DataCamp

การวนซ้ำด้วย for loop

  • สามารถวนซ้ำผ่านลิสต์ด้วย for loop
employees = ['Nick', 'Lore', 'Hugo']

for employee in employees: print(employee)
Nick
Lore
Hugo
Python Toolbox

การวนซ้ำด้วย for loop

  • สามารถวนซ้ำผ่านสตริงด้วย for loop
for letter in 'DataCamp':
    print(letter)
D
a
t
a
C
a
m
p
Python Toolbox

การวนซ้ำด้วย for loop

  • สามารถวนซ้ำผ่าน range object ด้วย for loop
for i in range(4):
    print(i)
0
1
2
3
Python Toolbox

Iterator กับ iterable

  • Iterable
    • ตัวอย่าง: ลิสต์, สตริง, ดิกชันนารี, การเชื่อมต่อไฟล์
    • อ็อบเจกต์ที่มีเมธอด iter() เชื่อมอยู่
    • การใช้ iter() กับ iterable จะสร้าง iterator
  • Iterator
    • ดึงค่าถัดไปด้วย next()
Python Toolbox

การวนซ้ำผ่าน iterable ด้วย 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 Toolbox

การวนซ้ำทีเดียวด้วย *

word = 'Data'
it = iter(word)

print(*it)
D a t a
print(*it)
  • ไม่มีค่าเหลือให้วนซ้ำแล้ว!
Python Toolbox

การวนซ้ำผ่านดิกชันนารี

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

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

การวนซ้ำผ่านการเชื่อมต่อไฟล์

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

print(next(it))
This is the first line.
print(next(it))
This is the second line.
Python Toolbox

มาฝึกกันเถอะ!

Python Toolbox

Preparing Video For Download...