Defaultdict with values defaulted to negative infinity

大城市里の小女人 提交于 2019-12-13 08:28:30

问题


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. How do I do this?


回答1:


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.

float('-inf') is not callable. Instead, you could do e.g.:

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

providing a callable "lambda expression" that returns the default value. It's for the same reason that you see code with e.g. defaultdict(int) rather than defaultdict(0):

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

You would also get similar issues when e.g. trying to nest defaultdicts within each other (see Python: defaultdict of defaultdict?).



来源:https://stackoverflow.com/questions/29901564/defaultdict-with-values-defaulted-to-negative-infinity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!