4.1 手动é��历è¿ä»£å™¨Â¶
问题¶
ä½ æƒ³é��历一个å�¯è¿ä»£å¯¹è±¡ä¸çš„æ‰€æœ‰å…ƒç´ ,但是å�´ä¸�想使用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 。
下�是示例:
with open('/etc/passwd') as f:
while True:
line = next(f, None)
if line is None:
break
print(line, end='')
讨论¶
大多数情况下,我们会使用 for 循环è¯å�¥ç”¨æ�¥é��历一个å�¯è¿ä»£å¯¹è±¡ã€‚
但是,å�¶å°”也需è¦�对è¿ä»£å�šæ›´åŠ ç²¾ç¡®çš„æŽ§åˆ¶ï¼Œè¿™æ—¶å€™äº†è§£åº•å±‚è¿ä»£æœºåˆ¶å°±æ˜¾å¾—尤为é‡�è¦�了。
下é�¢çš„交互示例å�‘我们演示了è¿ä»£æœŸé—´æ‰€å�‘生的基本细节:
>>> 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
>>>
æœ¬ç« æŽ¥ä¸‹æ�¥å‡ å°�节会更深入的讲解è¿ä»£ç›¸å…³æŠ€æœ¯ï¼Œå‰�æ��æ˜¯ä½ å…ˆè¦�ç�†è§£åŸºæœ¬çš„è¿ä»£å��议机制。 所以确ä¿�ä½ å·²ç»�æŠŠè¿™ç« çš„å†…å®¹ç‰¢ç‰¢è®°åœ¨å¿ƒä¸ã€‚