在字典中创建或追加列表 - 这可以简化吗?

82 投票
3 回答
40137 浏览
提问于 2025-04-16 06:50

这个Python代码能不能用itertools和集合来缩短一下,同时还能保持可读性呢?

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)])

3 个回答

6

可能有点慢,但能用

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

一个可以替代 defaultdict 的方法是使用标准字典的 setdefault 方法:

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

这个方法依赖于一个事实,那就是列表是可变的,也就是说从 setdefault 返回的列表和字典里存的那个列表是同一个,所以你可以直接往里面添加内容。

96

你可以使用一个叫做 defaultdict(list) 的东西。

from collections import defaultdict

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

撰写回答