迭代器入門

Python 工具箱

Hugo Bowne-Anderson

Data Scientist at DataCamp

用 for 迴圈迭代

  • 可用 for 迴圈遍歷 list
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. 可疊代物件

  • 可疊代物件(Iterable)
    • 例:list、字串、dictionary、檔案連線
    • 具備對應的 iter() 方法的物件
    • 對可疊代物件呼叫 iter() 會建立迭代器
  • 迭代器(Iterator)
    • 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 工具箱

一起來練習吧!

Python 工具箱

Preparing Video For Download...