Python迭代器/一个衬里用于循环 [英] Python iterators/ one liner for loop
本文介绍了Python迭代器/一个衬里用于循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能很明显,但是我对于是否可以使用迭代器/一个内衬来实现以下目标感到困惑:
This may be obvious, but I'm stuck as to whether I can use an iterator/one liner to achieve the following:
TEAMS = [u'New Zealand', u'USA']
dict = {}
我怎么写:
for team in TEAMS:
dict[team] = u'Rugby'
作为迭代器,例如:
(dict[team] = u'Rugby' for team in TEAMS) # Or perhaps
[dict[team] for team in TEAMS] = u'Rugby
可以做到吗,括号需要放在哪里?
Can it be done, where do the parentheses need to be placed?
必填输出:
dict = {u'New Zealand': u'Rugby', u'USA': u'Rugby'}
我知道在python中有很多与迭代器相关的问题,所以我很抱歉,如果有答案,我已经尝试过寻找,但找不到针对该特定问题的好答案.
I know there are lots of questions related to iterators in python, so I apologize if this has an answer, I have tried looking and couldn't find a good answer to this particular issue.
推荐答案
您可以使用dict理解.在下面看看:
You can use dict comprehension. Take a look below:
TEAMS = [u'New Zealand', u'USA']
d = {team: 'Rugby' for team in TEAMS}
这篇关于Python迭代器/一个衬里用于循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文