Python 2.5中增加的collections.defaultdict极大地减少了对dict的setdefault方法的需求。这个问题是为了我们的集体教育:
在今天的Python 2.6/2.7中,setdefault在哪些方面仍然有用? setdefault的哪些流行用例被collections.defaultdict所取代?
Python 2.5中增加的collections.defaultdict极大地减少了对dict的setdefault方法的需求。这个问题是为了我们的集体教育:
在今天的Python 2.6/2.7中,setdefault在哪些方面仍然有用? setdefault的哪些流行用例被collections.defaultdict所取代?
当前回答
正如Muhammad所说,在某些情况下,您只是偶尔希望设置默认值。一个很好的例子是数据结构,首先填充,然后查询。
考虑一个例子。在添加单词时,如果需要子节点但不存在,则必须创建子节点以扩展树。在查询单词是否存在时,缺少子节点表示该单词不存在,不应该创建它。
defaultdict不能这样做。相反,必须使用带有get和setdefault方法的常规dict。
其他回答
下面是一些setdefault的例子来展示它的有用性:
"""
d = {}
# To add a key->value pair, do the following:
d.setdefault(key, []).append(value)
# To retrieve a list of the values for a key
list_of_values = d[key]
# To remove a key->value pair is still easy, if
# you don't mind leaving empty lists behind when
# the last value for a given key is removed:
d[key].remove(value)
# Despite the empty lists, it's still possible to
# test for the existance of values easily:
if d.has_key(key) and d[key]:
pass # d has some values for key
# Note: Each value can exist multiple times!
"""
e = {}
print e
e.setdefault('Cars', []).append('Toyota')
print e
e.setdefault('Motorcycles', []).append('Yamaha')
print e
e.setdefault('Airplanes', []).append('Boeing')
print e
e.setdefault('Cars', []).append('Honda')
print e
e.setdefault('Cars', []).append('BMW')
print e
e.setdefault('Cars', []).append('Toyota')
print e
# NOTE: now e['Cars'] == ['Toyota', 'Honda', 'BMW', 'Toyota']
e['Cars'].remove('Toyota')
print e
# NOTE: it's still true that ('Toyota' in e['Cars'])
[编辑]大错特错!setdefault总是会触发long_computation,因为Python很急切。
扩展塔特尔的答案。对我来说,最好的用例是缓存机制。而不是:
if x not in memo:
memo[x]=long_computation(x)
return memo[x]
这需要3行和2到3次查找,我很乐意这样写:
return memo.setdefault(x, long_computation(x))
我经常使用setdefault,在字典中设置默认值(!!)通常是os。环境字典:
# Set the venv dir if it isn't already overridden:
os.environ.setdefault('VENV_DIR', '/my/default/path')
简单点说,是这样的:
# Set the venv dir if it isn't already overridden:
if 'VENV_DIR' not in os.environ:
os.environ['VENV_DIR'] = '/my/default/path')
值得注意的是,你也可以使用结果变量:
venv_dir = os.environ.setdefault('VENV_DIR', '/my/default/path')
但与违约之前相比,这已经不那么必要了。
defaultdict相对于dict (dict.setdefault)的一个缺点是,defaultdict对象每次给出不存在的键时都会创建一个新项(例如==,print)。此外,defaultdict类通常比dict类更不常见,它更难IME序列化。
注:IMO函数|方法不意味着改变对象,不应该改变对象。
除了上述建议之外,如果您不想修改已经设置的值,setdefault可能会很有用。例如,当你有重复的数字,你想把它们当作一组。在这种情况下,如果遇到已设置的重复键,则不会更新该键的值。您将保留第一次遇到的值。就好像你只迭代/更新重复的键一次。
下面是一个记录排序列表中键/元素索引的代码示例:
nums = [2,2,2,2,2]
d = {}
for idx, num in enumerate(sorted(nums)):
# This will be updated with the value/index of the of the last repeated key
# d[num] = idx # Result (sorted_indices): [4, 4, 4, 4, 4]
# In the case of setdefault, all encountered repeated keys won't update the key.
# However, only the first encountered key's index will be set
d.setdefault(num,idx) # Result (sorted_indices): [0, 0, 0, 0, 0]
sorted_indices = [d[i] for i in nums]