python 如果没有该key值置为空_没有键时Python字典的默认值

from collections import Counter

histogram = Counter()

...

histogram[n] += 1

对于数字以外的值,请查看collections.defaultdict。在本例中,您可以使用defaultdict(int)代替Counter,但是Counter添加了.elements()和{}等功能。defaultdict(list)是另一个非常有用的例子。在

Counter还有一个方便的构造函数。而不是:

^{pr2}$

你只需: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值