【问题标题】:Python dictionary default value when there is no key [duplicate]没有键时的Python字典默认值[重复]
【发布时间】:2017-09-06 02:19:15
【问题描述】:

有没有更优雅的方法来实现这一点:如果键存在,则将其值加一,否则创建键并将其值设置为 1。

histogram = {}
...
if histogram.has_key(n):
    histogram[n] += 1
else: 
    histogram[n] = 1

【问题讨论】:

    标签: python dictionary default


    【解决方案1】:
    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
    

    【讨论】:

    • How to Answer 中所述,请避免回答不清楚、宽泛、SW 推荐、错字、基于意见、不可复制或重复的问题。编写我的代码请求和省力的家庭作业问题对于Stack Overflow 来说是题外话,更适合专业的编码/辅导服务。好的问题坚持How to Ask,包括minimal reproducible example,有研究工作,并且有可能对未来的访问者有用。回答不恰当的问题会使网站更难导航并鼓励进一步提出此类问题,从而损害网站,这可能会赶走其他自愿提供时间和专业知识的用户。
    • @TigerhawkT3 我认为我的回答比您的任何一个重复问题都更好地涵盖了这个主题,下次出现这种问题时,我将链接到这个答案。我想要一个很好的规范的地方来一劳永逸地解决这个问题。
    • 我不同意。如果您仍然认为自己的答案更好,则应该将其发布到现有问题之一,因为回答完全相同的问题会使网站更难导航。
    • 确认:这是frowned upon after all。请不要为了宣传您的帖子而发布重复问题的重复答案。
    猜你喜欢
    • 2021-07-27
    • 2016-06-25
    • 2017-01-27
    • 2016-01-28
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    相关资源
    最近更新 更多