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

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

问题描述

我已经阅读了 python 文档中的示例,但仍然无法弄清楚该方法的含义.有人可以帮忙吗?这是python文档中的两个示例

<预><代码>>>>从集合导入 defaultdict>>>s = '密西西比'>>>d = defaultdict(int)>>>对于 s 中的 k:... d[k] += 1...>>>d.items()[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

<预><代码>>>>s = [('黄色', 1), ('蓝色', 2), ('黄色', 3), ('蓝色', 4), ('红色', 1)]>>>d = defaultdict(列表)>>>对于 k, v 在 s:... d[k].append(v)...>>>d.items()[('蓝色', [2, 4]), ('红色', [1]), ('黄色', [1, 3])]

参数intlist是干什么用的?

解决方案

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

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

>>> from collections import defaultdict

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

and

>>> 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])]

the parameters int and list are for what?

解决方案

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 to 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天全站免登陆