设置Python的collections.defaultdict的默认字符串值 [英] setting the default string value of Python's collections.defaultdict

查看:747
本文介绍了设置Python的collections.defaultdict的默认字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Python 3.2.3,并且要更改默认返回的字符串值:

  $ bd = defaultdict(str)
d [NonExistent]

返回的值为''。如何更改此值,以便在未找到键时返回未知而不是空字符串?

解决方案

defaultdict的参数是一个返回默认值的函数(或者更确切地说,一个可调用对象)。因此,您可以传入一个返回您所需默认值的lambda。

 >>从集合import defaultdict 
>>> d = defaultdict(lambda:'My default')
>>> d ['junk']
'我的默认'

p>

lambda只是定义一个函数而不给它一个名字的简写。你可以用一个明确的def来做同样的事情:

 >> def myDefault():
... return'我的默认'
>>>> d = defaultdict(myDefault)
>>>> d ['junk']
'我的默认'

请参阅文档了解详情。


I am using Python 3.2.3 and want to change the default returned string value:

from collections import defaultdict
d=defaultdict(str)
d["NonExistent"]

The value returned is ''. How can I change this so that when a key is not found, "unknown" is returned instead of the empty string?

解决方案

The argument to defaultdict is a function (or rather, a callable object) that returns the default value. So you can pass in a lambda that returns your desired default.

>>> from collections import defaultdict
>>> d = defaultdict(lambda: 'My default')
>>> d['junk']
'My default'

Edited to explain lambda:

lambda is just a shorthand for defining a function without giving it a name. You could do the same with an explicit def:

>>> def myDefault():
...     return 'My default'
>>>> d = defaultdict(myDefault)
>>> d['junk']
'My default'

See the documentation for more info.

这篇关于设置Python的collections.defaultdict的默认字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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