2014-05-21 42 views
-1

列表理解我有這樣的邏輯:一些平等行動蟒蛇

for need in we_need_this: 
    items_dict[need] = to_string_and_select(need) 

我該怎麼辦列表理解? 我想:

[items_dict[need] = to_string_and_select(need) for need in we_need_this] 

但does`t工作

回答

3

如果你開始用空items_dict,簡單的字典理解就足夠了。

items_dict = {x: to_string_and_select(x) for x in we_need_this} 

如果items_dict不爲空,則需要使用update方法來更新它:

items_dict.update({x: to_string_and_select(x) for x in we_need_this}) 

關於Python 2.6及以上使用dict((x, to_string_and_select(x)) for x in we_need_this),而不是字典理解。


有醜的方式來實現這一目標使用列表理解

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] 


+0

+1雖然它可能適合注意此方法只適用於python2.7 + ...對於python2.6或更低版本使用'dict([(k,v)for k,v in some_list])'(這也應該在2.7 +) –

+0

@JoranBeasley謝謝,更新。 – vaultah

2

由於items_dict是一本字典,使用items_dict.update和字典理解:

items_dict.update({ 
    need: to_string_and_select(need) for need in we_need_this 
}) 
+0

bravissimo,man !! – user2424174