Yield multiple values

前端 未结 3 434
长发绾君心
长发绾君心 2021-01-30 20:56

Can\'t we yield more than one value in the python generator functions?

Example,

In [677]: def gen():
   .....:     for i in range(5):
   .....:         y         


        
3条回答
  •  孤城傲影
    2021-01-30 21:12

    Because gen() returns a generator (a single item - so it can't be unpacked as two), it needs to be advanced first to get the values...

    g = gen()
    a, b = next(g)
    

    It works with list because that implicitly consumes the generator.

    Can we further make this a generator? Something like this:

    g = gen();
    def yield_g():
        yield g.next();
        k1,k2 = yield_g();
    

    and therefore list(k1) would give [0,1,2,3,4] and list(k2) would give [1,2,3,4,5].

    Keep your existing generator, and use izip (or zip):

    from itertools import izip
    k1, k2 = izip(*gen())
    

提交回复
热议问题