设置Python的collections.defaultdict的默认字符串值 [英] setting the default string value of Python's 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屋!