简体   繁体   English

Defaultdict,其值默认为负无穷大

[英]Defaultdict with values defaulted to negative infinity

I want to create a default dictionary in which the default values are negative infinity. 我想创建一个默认字典,其中默认值为负无穷大。 I tried doing defaultdict(float("-inf")) but it is not working. 我尝试做defaultdict(float("-inf"))但是没有用。 How do I do this? 我该怎么做呢?

As the traceback specifically tells you : 正如追溯明确告诉您的那样

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

and per the documentation (emphasis mine): 根据文档 (重点是我的):

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. 如果default_factory [ defaultdict的第一个参数]不为None ,则在不带参数的情况下调用该函数以提供给定键的默认值,此值将插入键的字典中并返回。

float('-inf') is not callable. float('-inf')不可调用的。 Instead, you could do eg: 相反,您可以执行例如:

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

providing a callable "lambda expression" that returns the default value. 提供可返回默认值的可调用“ lambda表达式” It's for the same reason that you see code with eg defaultdict(int) rather than defaultdict(0) : 出于同样的原因,您看到的代码包含defaultdict(int)而不是defaultdict(0)

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

You would also get similar issues when eg trying to nest defaultdict s within each other (see Python: defaultdict of defaultdict? ). 例如,当尝试将defaultdict彼此嵌套时,您也会遇到类似的问题(请参阅Python:defaultdict的defaultdict? )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM