问题描述
我正在检查Peter Norvig的,了解如何编写简单的拼写检查器。开始时,他使用这段代码将字词插入字典。
def train(features):
model = collections.defaultdict(lambda:1)
for f in features:
model [f] + = 1
return model
Python dict和这里使用的Python dict有什么区别?另外,什么是 lambda
?我检查了API文档,它表示defaultdict实际上是从dict派生而是一个决定哪一个使用?
区别在于一个 defaultdict
如果该键尚未设置,将会默认一个值。如果您没有使用 defaultdict
,则必须检查该密钥是否存在,如果没有,请将其设置为您想要的。 p>
lambda为默认值定义工厂。该函数在需要默认值时被调用。您可以假设有一个更复杂的默认功能。
模块集合中的类defaultdict帮助:
class defaultdict(__ builtin __。dict)
| defaultdict(default_factory) - > dict的默认工厂
|
|调用默认工厂无参数生成
|一个键值不存在时的新值,仅在__getitem__中。
| defaultdict与相同项目的dict相等。
|
(来自 help(type(collections.defaultdict())) code>)
{}。setdefault
本质上类似,但是接受一个值,而不是一个工厂功能。它用于设置值,如果它不存在...这有点不同,但是。
I was checking out Peter Norvig's code on how to write simple spell checkers. At the beginning, he uses this code to insert words into a dictionary.
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
What is the difference between a Python dict and the one that was used here? In addition, what is the lambda
for? I checked the API documentation here and it says that defaultdict is actually derived from dict but how does one decide which one to use?
The difference is that a defaultdict
will "default" a value if that key has not been set yet. If you didn't use a defaultdict
you'd have to check to see if that key exists, and if it doesn't, set it to what you want.
The lambda is defining a factory for the default value. That function gets called whenever it needs a default value. You could hypothetically have a more complicated default function.
Help on class defaultdict in module collections:
class defaultdict(__builtin__.dict)
| defaultdict(default_factory) --> dict with default factory
|
| The default factory is called without arguments to produce
| a new value when a key is not present, in __getitem__ only.
| A defaultdict compares equal to a dict with the same items.
|
(from help(type(collections.defaultdict()))
)
{}.setdefault
is similar in nature, but takes in a value instead of a factory function. It's used to set the value if it doesn't already exist... which is a bit different, though.
这篇关于dict和collections.defaultdict有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!