天天看點

python疊代器和生成python疊代器和生成

python疊代器和生成

手動周遊疊代器

目的:

想周遊一個可疊代對象中的所有元素,卻不想用for循環

解析:

為了手動的周遊可疊代對象,使用 next() 函數并在代碼中捕獲 StopIteration 異常。

def manual_iter():
	with open('/etc/passwd') as f:
		try:
			while True:
				line = next(f)
				print(line, end='')
		except StopIteration:
			pass
           

StopIteration 用來訓示疊代的結尾

如果手動使用上面示範的 next() 函數的話,還可以通過傳回一個指定值來标記結尾,比如 None

疊代期間所發生的基本細節

>>> items = [1, 2, 3]
>>> # Get the iterator
>>> it = iter(items) # Invokes items.__iter__()
>>> # Run the iterator
>>> next(it) # Invokes it.__next__()
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
           

繼續閱讀