2010-11-10 20 views
33

可以使用itertools和set來縮短這個Python代碼並仍然可讀嗎?創建或追加到字典中的列表 - 可以縮短嗎?

result = {} 
for widget_type, app in widgets: 
    if widget_type not in result: 
     result[widget_type] = [] 
    result[widget_type].append(app) 

我覺得這只是:

widget_types = zip(*widgets)[0] 
dict([k, [v for w, v in widgets if w == k]) for k in set(widget_types)]) 

回答

34

可以使用defaultdict(list)

from collections import defaultdict 

result = defaultdict(list) 
for widget_type, app in widgets: 
    result[widget_type].append(app) 
+0

從來不知道這一點。涼! – 2010-11-10 11:04:06

66

defaultdict另一種方法是使用標準字典的setdefault方法:

result = {} 
for widget_type, app in widgets: 
    result.setdefault(widget_type, []).append(app) 

這依賴於一個事實,即列表是可變的,那麼什麼是從setdefault返回相同列表作爲一個在字典中,因此你可以追加到它。

+1

這就是我今天學習Python的東西。謝謝,丹尼爾。 :) – Walter 2010-11-10 12:39:08

4

可能會有點慢,但工作

result = {} 
for widget_type, app in widgets: 
    result[widget_type] = result.get(widget_type, []) + [app] 
+0

爲什麼這會比其他解決方案慢? – 2017-07-18 14:35:18