Python 用一些相等的动作列出理解
我有这样的逻辑:Python 用一些相等的动作列出理解,python,list-comprehension,Python,List Comprehension,我有这样的逻辑: for need in we_need_this: items_dict[need] = to_string_and_select(need) 我怎样做列表理解? 我试过: 但是它不起作用,如果你从空的单词开始,简单的单词理解就足够了 items_dict = {x: to_string_and_select(x) for x in we_need_this} 如果items\u dict不为空,则需要使用以下方法更新它: 在Python2.6和更早版本中,我们需
for need in we_need_this:
items_dict[need] = to_string_and_select(need)
我怎样做列表理解?
我试过:
但是它不起作用,如果你从空的单词开始,简单的单词理解就足够了
items_dict = {x: to_string_and_select(x) for x in we_need_this}
如果items\u dict
不为空,则需要使用以下方法更新它:
在Python2.6和更早版本中,我们需要使用dict((x,to_string_和_select(x))代替dict理解
使用列表理解有很多难看的方法来实现这一点
from operator import setitem
[setitem(items_dict, x, to_string_and_select(x)) for x in we_need_this]
或
由于items\u dict
是一本词典,请使用items\u dict.update
和dict comprehension:
items_dict.update({
need: to_string_and_select(need) for need in we_need_this
})
+1尽管可能需要注意的是,该方法仅适用于python2.7+。。。对于python2.6或更低版本,请使用dict([(k,v)表示某些列表中的k,v])
(在2.7+中也应适用)
from operator import setitem
[setitem(items_dict, x, to_string_and_select(x)) for x in we_need_this]
[items_dict.__setitem__(x, to_string_and_select(x)) for x in we_need_this]
items_dict.update({
need: to_string_and_select(need) for need in we_need_this
})