[英]Pythonic way of adding items to a dict of lists
我经常使用这个片段:
d = {}
for x in some_list:
y = some_func(x) # can be identity
if y in d:
d[y].append(another_func(x))
else:
d[y] = [another_func(x)]
这是最pythonic的方法还是有更好的方法? 我使用 Python 3。
你可以试试
from collections import defaultdict
d = defaultdict(list)
for x in some_list:
d[some_func(x)].append(another_func(x))
defaultdict 是一个字典选项,您可以使用要分配的类型对其进行初始化,以防您要查找的键在字典的键中不存在。 在这种情况下,每次调用 d 如果键不存在,它将创建一个空列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.