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
  • 相关阅读:
    Lua 的元表怎么理解
    Lua中的元表与元方法
    Lua 的元表怎么理解
    VMware Workstation 系统备份-虚拟机克隆方法
    Lua中的元表与元方法
    bzoj2809
    bzoj2733
    bzoj1334
    bzoj1211
    bzoj3083 3306
  • 原文地址:https://www.cnblogs.com/111testing/p/13906458.html
Copyright © 2011-2022 走看看