一、面试问题假如你去面试,面试官无聊地问你:如何不使用for循环打印出一个可迭代对象中所有元素,你该如何应对呢?
二、应对方式2.1 StopIteration中止法即然不能使用for循环,当然也不可能一个一个输出next()来输出,因此我们想到了while循环,但是使用while循环就必须要有一个中止条件。通过上一章《python进阶——生成器系列之迭代器与反向迭代》的基础学习,我们可以在代码中捕获StopIteration异常。比如下面例子中手动读取一个文件中的所有行:
def manual_iter(): with open('/etc/profile') as fp: try: while True: line = next(fp) print(line, end='') except StopIteration: pass2.2 通过返回值为None来中止使用StopIteration来标识迭代结尾,但是还有另外一种更简单的方式,可以通过返回一个指定值来标记结尾,比如None。
with open('/etc/profile') as fp: while True: line = next(fp, 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 "", line 1, in StopIteration>>>这个例子演示了迭代时所发生的基本细节:每next()一次迭代对象就会返回该对象的一个元素,当迭代对象被遍历完时,则会抛出StopIteration异常。