zoukankan      html  css  js  c++  java
  • python3: 迭代器与生成器(1)

    1. 手动遍历迭代器

    你想遍历一个可迭代对象中的所有元素,但是却不想使用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
    >>>

    2. 代理迭代

    3.使用生成器创建新的迭代模式

    一个函数中需要有一个 yield 语句即可将其转换为一个生成器。 跟普通函数不同的是,生成器只能用于迭代操作

    >>> def countdown(n):
    ...     print('Starting to count from', n)
    ...     while n > 0:
    ...         yield n
    ...         n -= 1
    ...     print('Done!')
    ...
    
    >>> # Create the generator, notice no output appears
    >>> c = countdown(3)
    >>> c
    <generator object countdown at 0x1006a0af0>
    
    >>> # Run to first yield and emit a value
    >>> next(c)
    Starting to count from 3
    3
    
    >>> # Run to the next yield
    >>> next(c)
    2
    
    >>> # Run to next yield
    >>> next(c)
    1
    
    >>> # Run to next yield (iteration stops)
    >>> next(c)
    Done!
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    StopIteration
    >>>

    4. 实现迭代器协议

    5. 反向迭代

    6.带有外部状态的生成器函数

    7.迭代器切片

    函数 itertools.islice() 正好适用于在迭代器和生成器上做切片操作。比如:

    >>> def count(n):
    ...     while True:
    ...         yield n
    ...         n += 1
    ...
    >>> c = count(0)
    >>> c[10:20]
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    TypeError: 'generator' object is not subscriptable
    
    >>> # Now using islice()
    >>> import itertools
    >>> for x in itertools.islice(c, 10, 20):
    ...     print(x)
    ...
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    8. 跳过可迭代对象的开始部分

    场景:你想遍历一个可迭代对象,但是它开始的某些元素你并不感兴趣,想跳过它们。

    >>> from itertools import dropwhile
    >>> with open('/etc/passwd') as f:
    ...     for line in dropwhile(lambda line: line.startswith('#'), f):
    ...         print(line, end='')
    ...

    如果你已经明确知道了要跳过的元素的个数的话,那么可以使用 itertools.islice() 来代替。

     
  • 相关阅读:
    JS基础学习
    Java_iText_PDF—生成PDF工具
    vc++ 编译连接错误and解决方法
    C++ 数据类型【转】
    jsp两种include指令区别
    程序员面试宝典问题及解析
    vc++6.0快捷键
    vue动态绑定图片和背景图
    配置webpack中dev.env.js、prod.env.js,解决不同命令下项目启动和打包到指定的环境
    配置webpack中externals来减少打包后vendor.js的体积
  • 原文地址:https://www.cnblogs.com/xiyuan2016/p/10345997.html
Copyright © 2011-2022 走看看