【发布时间】:2017-09-06 02:19:15
【问题描述】:
有没有更优雅的方法来实现这一点:如果键存在,则将其值加一,否则创建键并将其值设置为 1。
histogram = {}
...
if histogram.has_key(n):
histogram[n] += 1
else:
histogram[n] = 1
【问题讨论】:
标签: python dictionary default
有没有更优雅的方法来实现这一点:如果键存在,则将其值加一,否则创建键并将其值设置为 1。
histogram = {}
...
if histogram.has_key(n):
histogram[n] += 1
else:
histogram[n] = 1
【问题讨论】:
标签: python dictionary default
from collections import Counter
histogram = Counter()
...
histogram[n] += 1
对于数字以外的值,请查看collections.defaultdict。在这种情况下,您可以使用defaultdict(int) 代替Counter,但Counter 添加了.elements() 和.most_common() 等功能。 defaultdict(list) 是另一个非常有用的例子。
Counter 也有一个方便的构造函数。而不是:
histogram = Counter()
for n in nums:
histogram[n] += 1
你可以这样做:
histogram = Counter(nums)
其他选项:
histogram.setdefault(n, 0)
histogram[n] += 1
和
histogram[n] = histogram.get(n, 0) + 1
在列表的情况下,setdefault 可能更有用,因为它返回值,即:
dict_of_lists.setdefault(key, []).append(value)
作为最后的奖励,现在有点偏离轨道,这是我最常用的defaultdict:
def group_by_key_func(iterable, key_func):
"""
Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements
of the iterable and the values are lists of elements all of which correspond to the key.
>>> dict(group_by_key_func("a bb ccc d ee fff".split(), len)) # the dict() is just for looks
{1: ['a', 'd'], 2: ['bb', 'ee'], 3: ['ccc', 'fff']}
>>> dict(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2))
{0: [0, 6, 8, 2], 1: [-1, 1, 3, 9]}
"""
result = defaultdict(list)
for item in iterable:
result[key_func(item)].append(item)
return result
【讨论】: