python yield关键字作用
2020-10-31 15:28 清风软件测试开发 阅读(154) 评论(0) 收藏 举报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