问题
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 todefaultdict] is notNone, 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