python,yield理解
迭代对象:
mygene = [x * x for x in range(3)] print(mygene) #[0, 1, 4] for i in mygene: print(i)
生成器:
mygene = (x * x for x in range(3)) print(mygene) #<generator object <genexpr> at 0x0000000002993F68> for i in mygene: #只打印一次 print(i) for i in mygene: #这里不生效 print(i)
Yield:
def createGenerator(): mylist = range(3) for i in mylist: yield i * i mygenerator = createGenerator() print(mygenerator) for i in mygenerator: print(i)
返回值:
def bar(): a = 10 return a def foo(): a = 10 yield a a = bar() #10 b = foo() #<generator object foo at 0x00000000020DAFC0> print(a) print(b)
小结:
1.Yield是关键字,它类似于return,只是函数会返回一个生成器。
2.生成器是一个可迭代对象,类似于一个某种算法的函数,它不用生成在内存,只有在调用时才显示
3.只能迭代一次
4.函数返回的是值,生成器返回的是生成对象
这个不太容易理解,要多看几遍
参考资料:
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000
https://foofish.net/understanding-yield.html