问题描述
举一个人为的例子:
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
.
这就是发生的事情:
-
list
调用next(mydict)
. - Yield将
''.join([item, 's'])
返回到list
并冻结了理解. -
list
调用next(mydict)
. - 继续理解,并将
yield
(None
)的结果分配给字典中的item
并开始新的理解迭代. - 回到1.
list
callsnext(mydict)
.- Yield returns
''.join([item, 's'])
tolist
and freezes the comprehension. list
callsnext(mydict)
.- The comprehension resumes and assigns the result of
yield
(None
) toitem
in the dictionary and starts a new comprehension iteration. - 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!