迭代器简介

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 工具箱

Vamos praticar!

Python 工具箱

Preparing Video For Download...