本文介绍了使用dict理解的yield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举一个人为的例子:

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

list(mydict)给出:

['as', 'cs', 'bs', 'ds', {'a': None, 'b': None, 'c': None, 'd': None}]

这里发生了什么? yield的作用是什么?不管yield后面是什么表达式,这种行为都是一致的吗?

What happens here? What does yield do? And is this behavior consistent no matter what expression follows yield?

注意:我知道做mydict = {item: ''.join([item, 's']) for item in myset}会得到字典{'a': 'as', 'b': 'bs', 'c': 'cs', 'd': 'ds'},这似乎是我在这里尝试做的事情.

Note: I know that doing mydict = {item: ''.join([item, 's']) for item in myset} would give the dictionary {'a': 'as', 'b': 'bs', 'c': 'cs', 'd': 'ds'}, which seems to be what I am trying to do here.

推荐答案

首先,yield返回什么?在这种情况下的答案是None,因为yield返回传递给next()的参数,在这种情况下没有任何结果(list不会将任何内容传递给next).

First of all, what does yield return? The answer in this case is None, because yield returns the parameter passed to next(), which is nothing in this case (list doesn't pass anything to next).

现在这是您的答案:

>>> myset = set(['a', 'b', 'c', 'd'])
>>> mydict = {item: (yield ''.join([item, 's'])) for item in myset}
>>> mydict
<generator object <dictcomp> at 0x0222BB20>

dict理解将变成生成器,因为您在函数体上下文中使用了yield!这意味着直到将其传递到list为止,整个内容都不会进行评估.

The dict comprehension is turned into a generator, because you used yield in a function body context! This means that the whole thing isn't evaluated until it's passed into list.

这就是发生的事情:

  1. list调用next(mydict).
  2. Yield将''.join([item, 's'])返回到list并冻结了理解.
  3. list调用next(mydict).
  4. 继续理解,并将yield(None)的结果分配给字典中的item并开始新的理解迭代.
  5. 回到1.
  1. list calls next(mydict).
  2. Yield returns ''.join([item, 's']) to list and freezes the comprehension.
  3. list calls next(mydict).
  4. The comprehension resumes and assigns the result of yield (None) to item in the dictionary and starts a new comprehension iteration.
  5. Go back to 1.

最后,实际的生成器对象返回了主体中的临时对象,即dict.为什么会发生这种情况,我不知道,而且也可能没有记录在案的行为.

And at last the actual generator object returns the temporary in the body, which was the dict. Why this happens is unknown to me, and it's probably not documented behaviour either.

这篇关于使用dict理解的yield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:50