• python 生成器


    一 

    # Initialize the list
    my_list = [1, 3, 6, 10]
    
    # square each term using list comprehension
    # Output: [1, 9, 36, 100]
    [x**2 for x in my_list]
    
    # same thing can be done using generator expression
    # Output: <generator object <genexpr> at 0x0000000002EBDAF8>
    (x**2 for x in my_list)

    # Intialize the list
    my_list = [1, 3, 6, 10]
    
    a = (x**2 for x in my_list)
    # Output: 1
    print(next(a))
    
    # Output: 9
    print(next(a))
    
    # Output: 36
    print(next(a))
    
    # Output: 100
    print(next(a))
    
    # Output: StopIteration
    next(a)

    例子1

    #!/usr/bin/python3
    #coding=utf-8
    
    def my_gen():
        n = 1
        print('This is printed first, n= ', n)
        # Generator function contains yield statements
        yield n
    
        n += 1
        print('This is printed second, n= ', n)
        yield n
    
        n += 1
        print('This is printed at last, n= ', n)
        yield n

    输出

    >>> # It returns an object but does not start execution immediately.
    >>> a = my_gen()
    
    >>> # We can iterate through the items using next().
    >>> next(a)
    This is printed first, n = 1
    1
    >>> # Once the function yields, the function is paused and the control is transferred to the caller.
    
    >>> # Local variables and theirs states are remembered between successive calls.
    >>> next(a)
    This is printed second, n = 2
    2
    
    >>> next(a)
    This is printed at last, n = 3
    3
    
    >>> # Finally, when the function terminates, StopIteration is raised automatically on further calls.
    >>> next(a)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> next(a)
    Traceback (most recent call last):
    ...
    StopIteration

    例子2

    # A simple generator function
    def my_gen():
        n = 1
        print('This is printed first')
        # Generator function contains yield statements
        yield n
    
        n += 1
        print('This is printed second')
        yield n
    
        n += 1
        print('This is printed at last')
        yield n
    
    # Using for loop
    for item in my_gen():
        print(item)

    输出

    This is printed first
    1
    This is printed second
    2
    This is printed at last
    3

    例子3

    反转字符串的生成器

    def rev_str(my_str):
        length = len(my_str)
        for i in range(length - 1,-1,-1):
            yield my_str[i]
    
    for char in rev_str("hello"):
         print(char)

    输出

    o
    l
    l
    e
    h

  • 相关阅读:
    Web开发四大作用域(转)
    jsp与servlet(转)
    使用jsp,tomcat实现用户登录注册留言的代码
    java环境变量的配置
    JSP 九大内置对象(转)
    http协议头文件的控制信息(转)
    javaScript实现图片滚动及一个普通图片轮播的代码
    javaScript显示实时时间输出
    javaScript判断输入框是否为空
    1072 威佐夫游戏
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10178292.html
Copyright © 2020-2023  润新知