Use of yield with a dict comprehension

前端 未结 4 911
醉梦人生
醉梦人生 2021-02-07 01:53

As a contrived example:

myset = set([\'a\', \'b\', \'c\', \'d\'])
mydict = {item: (yield \'\'.join([item, \'s\'])) for item in myset}

and

4条回答
  •  轮回少年
    2021-02-07 02:34

    I think that yield is turning your nice dictionary comprehension into a generator expression. So, when you're iterating over the generator, yield is "yielding" the elements that look as, bs ..., but the statement yield ... returns None. So, at the end of the day, you get a dictionary looking like {'a': None, 'b': None, ...}.

    The part that confuses me is why the dictionary is actually yielded at the end. I'm guessing that this behavior is actually not well defined by the standard, but I could be wrong about that.

    Interestingly enough, if you try this with a list comprehension, python complains:

    >>> a = [(yield i) for i in myset]
      File "", line 1
    SyntaxError: 'yield' outside function
    

    But it's Ok in a generator (apparently).

提交回复
热议问题