zoukankan      html  css  js  c++  java
  • 手动遍历迭代器

    4.1 手动遍历迭代器:
    
    你想遍历一个可迭代对象中的所有元素,但是却不想使用for循环:
    
    解决方案:
    
    为了手动的遍历可迭代对象,使用next()函数并在代码中捕获StopIteration异常。
    
    [root@node01 python]# cat t1.py 
    def manual_iter():
       with open('hosts') as f:
            while True:
              line = next(f)
              print line.strip()
    manual_iter()
    
    
    [root@node01 python]# python t1.py 
    11111111
    22222222
    33333333
    Traceback (most recent call last):
      File "t1.py", line 6, in <module>
        manual_iter()
      File "t1.py", line 4, in manual_iter
        line = next(f)
    StopIteration
    
    
    通常来讲,StopIteration 用来指示迭代的结尾。然而,如果你手动使用上面的演示的话。
    
    
    
    [root@node01 python]# cat t1.py 
    def manual_iter():
       with open('hosts') as f:
          try:
            while True:
              line = next(f)
              print line.strip()
          except StopIteration:
              pass
    manual_iter()
    [root@node01 python]# python t1.py 
    11111111
    22222222
    33333333
    0
    
    大多数情况下,我们会使用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
    

  • 相关阅读:
    自动生成 serialVersionUID 的设置
    常见的HTTP状态码(HTTP Status Code)说明
    PowerDesigner 创建表格及导出SQL语句
    简历
    idea+Maven+SSM框架增删改查
    @Resource和@Autowired的区别
    SSM java.lang.NullPointerException
    多进程和多线程的优缺点(二)
    多进程和多线程的优缺点
    基于swoole扩展实现真正的PHP数据库连接池
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349468.html
Copyright © 2011-2022 走看看