Defaultdict 的值默认为负无穷大

Defaultdict with values defaulted to negative infinity

我想创建一个默认字典,其中默认值为负无穷大。我试过 defaultdict(float("-inf")) 但它不起作用。我该怎么做?

回溯明确告诉你:

>>> from collections import defaultdict
>>> dct = defaultdict(float('-inf'))

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    dct = defaultdict(float('-inf'))
TypeError: first argument must be callable

per the documentation(强调我的):

If default_factory [the first argument to defaultdict] is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

float('-inf') 不可 调用。相反,您可以这样做:

dct = defaultdict(lambda: float('-inf'))

提供可调用的 "lambda expression",returns 默认值。这与您看到带有例如代码的原因相同。 defaultdict(int) 而不是 defaultdict(0):

>>> int()  # callable
0  # returns the desired default value

你也会遇到类似的问题,例如试图将 defaultdict 彼此嵌套(参见 Python: defaultdict of defaultdict?)。