Python 在for循环中使用append方法
我目前正在查看Think Python使用setdefault方法实现反向字典的代码片段,我不清楚它为什么会工作:Python 在for循环中使用append方法,python,Python,我目前正在查看Think Python使用setdefault方法实现反向字典的代码片段,我不清楚它为什么会工作: def invert_dict(d): """Inverts a dictionary, returning a map from val to a list of keys. If the mapping key->val appears in d, then in the new dictionary val maps to a list that includes k
def invert_dict(d):
"""Inverts a dictionary, returning a map from val to a list of keys.
If the mapping key->val appears in d, then in the new dictionary
val maps to a list that includes key.
d: dict
Returns: dict
"""
inverse = {}
for key, val in d.iteritems():
inverse.setdefault(val, []).append(key)
return inverse
在for循环中从左到右读取,
inverse.setdefault(val,[])
在字典中创建一个条目,而不是列表。那么我们如何使用append方法呢?您可以使用append方法,因为setdefault本身会在必要时初始化dict[val]后返回其值。因此,第一次对特定字典键调用setdefault时,它将inverse[val]设置为第二个参数(空列表),然后返回该空列表。这是您要附加到的列表
顺便说一句,这个特定的范例对于这个特定的用例来说已经过时了。现在最好的方法是:
import collections
inverse = collections.defaultdict(list)
for key, val in d.items():
inverse[val].append(key)
原因是setdefault每次通过列表创建一个新的空列表对象,然后如果反向[val]已经存在,则立即丢弃新创建的对象
此外,iteritems()对于Python2仍然更有效,但它在Python3中不存在,Python3中的items()与Python2中的iteritems()工作原理相同。可能的重复项也请参见。