zoukankan      html  css  js  c++  java
  • 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 。下面是示例:

    with open('/etc/passwd') as f:
        while True:
            line = next(f)
            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
    >>>
    
  • 相关阅读:
    Hrbust-1492 盒子(二分图最大匹配)
    数据结构——二叉树的建立和遍历(递归建树&层序遍历建树)
    HDU 1710 二叉树遍历
    HDU 2891
    HDU 2895 贪心 还是 大水题
    POJ 2896 另解暴力
    POJ 2896 AC自动机 or 暴力
    HDU 1714 math
    POJ 1328 贪心
    POJ 2109 巧妙解法
  • 原文地址:https://www.cnblogs.com/baxianhua/p/9951922.html
Copyright © 2011-2022 走看看