这个 Python 代码能否被缩短并且仍然可以使用 itertools 和 set 读取?
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)])
最佳答案
defaultdict
的替代方法是使用标准字典的 setdefault
方法:
result = {}
for widget_type, app in widgets:
result.setdefault(widget_type, []).append(app)
这依赖于列表是可变的这一事实,因此从 setdefault 返回的列表与字典中的列表相同,因此您可以附加到它。
关于python - 创建或附加到字典中的列表 - 可以缩短吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4143698/