Attempting to understand yield as an expression

后端 未结 5 1819
猫巷女王i
猫巷女王i 2021-01-18 14:59

I\'m playing around with generators and generator expressions and I\'m not completely sure that I understand how they work (some reference material):

>>         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 15:10

    You're confusing yourself a bit because you actually are generating from two sources: the generator expression (... for x in range(10)) is one generator, but you create another source with the yield. You can see that if do list(a) you'll get [0, None, 1, None, 2, None, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None].

    Your code is equivalent to this:

    >>> def gen():
    ...     for x in range(10):
    ...         yield (yield x)
    

    Only the inner yield ("yield x") is "used" in the generator --- it is used as the value of the outer yield. So this generator iterates back and forth between yielding values of the range, and yielding whatever is "sent" to those yields. If you send something to the inner yield, you get it back, but if you happen to send on an even-numbered iteration, the send is sent to the outer yield and is ignored.

提交回复
热议问题