没有键时Python字典的默认值

Ros*_*den 0 python dictionary default

是否有更优雅的方法来实现此目的:如果密钥存在,则将其值增加1,否则创建密钥并将其值设置为1.

histogram = {}
...
if histogram.has_key(n):
    histogram[n] += 1
else: 
    histogram[n] = 1
Run Code Online (Sandbox Code Playgroud)

Ale*_*all 5

from collections import Counter
histogram = Counter()
...
histogram[n] += 1
Run Code Online (Sandbox Code Playgroud)

对于数字以外的值,请查看collections.defaultdict.在这种情况下,你可以使用defaultdict(int)替代的Counter,但Counter增加了功能,如.elements().most_common().defaultdict(list)是另一个非常有用的例子.

Counter还有一个方便的构造函数.代替:

histogram = Counter()
for n in nums:
    histogram[n] += 1
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

histogram = Counter(nums)
Run Code Online (Sandbox Code Playgroud)

其他选择:

histogram.setdefault(n, 0)
histogram[n] += 1
Run Code Online (Sandbox Code Playgroud)

histogram[n] = histogram.get(n, 0) + 1
Run Code Online (Sandbox Code Playgroud)

在列表的情况下,它setdefault可以更有用,因为它返回值,即:

dict_of_lists.setdefault(key, []).append(value)
Run Code Online (Sandbox Code Playgroud)

作为最后的奖金,现在略微偏离轨道,这是我最常用的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
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

2938 次

最近记录:

8 年,9 月 前