python cookbook 4.1 手动遍历迭代器

#想遍历一个可迭代对象所有元素,但不想使用for循环。使用next()函数,但注意要捕获StopIteration异常
def manual_iter():
    with open('/path') as f:
        try:
            while True:
                line = next(f)
                print(line,end='')
        except StopIteration:
            pass
#StopIteration用来指示迭代的结尾,若手动使用上面演示的next()函数的话,可以通过返回一个指定值标记结尾,比如Bone
def manual_iter1():
    with open('path/file') as f:
        while True:
            line = next(f,None)   #标记以None结尾
            if line is None:
                break
            print(line,end='')
#多数情况下会使用for循环语句用来遍历一个可迭代对象,偶尔也需要对迭代做更加精确的控制
items=[1,2,3]
it=iter(items)
print(next(it))
print(next(it))
print(next(it))
print(next(it))

python cookbook 4.1 手动遍历迭代器_第1张图片

你可能感兴趣的:(#,python,#,python,cookbook,python手动遍历迭代器,python,cookbook,4.1)