zoukankan      html  css  js  c++  java
  • python yield关键字作用

    python yield关键字作用

    1,是当前对象变成一个可迭代对象

    def frange(start,stop,step):
        x = start
        while x<stop:
            yield  x
            x+=step
    
    for i in frange(10,20,2.5):
        print(i)
    
    10
    12.5
    15.0
    17.5
    
    ============下面是没有yield的情况===========
    def frange(start,stop,step):
        x = start
        while x<stop:
            # yield  x
            x+=step
    
    for i in frange(10,20,2.5):
        print(i)
    
    TypeError: 'NoneType' object is not iterable
    
    
    ============下面是用list替代yield的情况===========
    def frange(start,stop,step):
        x = start
        a =[]
        while x<stop:
            # yield  x
            x+=step
            a.append(x)
        return a
    
    for i in frange(10,20,2.5):
        print(i)
    
    12.5
    15.0
    17.5
    20.0

    2,起到暂停作用,是被迭代的元素一个一个的被迭代,否则就会被for/while一次性循环

    def frange(start,stop,step):
        x = start
        while x<stop:
            yield  x
            x+=step
    
    it = frange(10,20,2)
    print(next(it))    #10
    print(next(it))    #12
    print(next(it))    #14
    print(next(it))    #16
    print(next(it))    #18
    print(next(it))    #StopIteration
  • 相关阅读:
    Catalan数
    C# & LINQ 对象克隆
    Rotate Image
    反转链表
    QtCreator调试程序时GDB崩溃
    Regular Expression Matching
    Wildcard Matching
    DFA与NFA
    Set Matrix Zeroes
    PCA原理
  • 原文地址:https://www.cnblogs.com/111testing/p/13906458.html
Copyright © 2011-2022 走看看