我经常使用此代码段:
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)]
这是最Python化的方法吗?还是有更好的方法?我使用Python 3。
答案 0 :(得分:0)
您可以尝试
from collections import defaultdict
d = defaultdict(list)
for x in some_list:
d[some_func(x)].append(another_func(x))
defaultdict是一个字典选项,如果要查找的键不存在于字典键中,则可以使用您要分配的类型来初始化它。 在这种情况下,如果键不存在,则每次调用d时,都会创建一个空列表。