collections.defaultdict如何工作? [英] How does collections.defaultdict work?

查看:101
本文介绍了collections.defaultdict如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了python文档中的示例,但仍然无法弄清楚这种方法的意思。有人可以帮忙吗?以下是python文档的两个示例:

I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

参数 int 列表是为什么?

推荐答案

通常,如果您尝试使用Python字典,则会抛出 KeyError 获取一个不在字典中的键的项目。相反, defaultdict 只会创建您尝试访问的任何项目(当然,这些项目当然不存在)。要创建这样一个默认项目,它调用您在构造函数中传递的函数对象(更准确地说,它是一个任意的可调用对象,其中包含函数和类型对象)。对于第一个示例,使用 int()创建默认项,这将返回整数对象 0 。对于第二个示例,使用 list()创建默认项,该项返回一个新的空列表对象。

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass in the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int(), which will return the integer object 0. For the second example, default items are created using list(), which returns a new empty list object.

这篇关于collections.defaultdict如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆