When each key is encountered for the first time, it is not already in
the mapping; so an entry is automatically created using the
default_factory function which returns an empty list. The
list.append() operation then attaches the value to the new list. When
keys are encountered again, the look-up proceeds normally (returning
the list for that key) and the list.append() operation adds another
value to the list. This technique is simpler and faster than an
equivalent technique using dict.setdefault():
>>> d = {}
>>> for k, v in s:
d.setdefault(k, []).append(v)
最好使用^{} 来处理这个问题,如果键值映射还不存在,它将自动创建任何被访问的键值映射。将可调用的函数传递给
defaultdict
构造函数,该构造函数将用于初始化值。例如:使用理解:
使用
dict.setdefault()
:使用
defaultdict
:输出:
相关问题 更多 >
编程相关推荐