我跑到下面的代码:defaultdict:第一个参数必须是可调用或无
from collections import defaultdict
lst = list(range(0,5))
d = defaultdict(lst)
,我得到这个错误:
TypeError: first argument must be callable or None
请帮
我跑到下面的代码:defaultdict:第一个参数必须是可调用或无
from collections import defaultdict
lst = list(range(0,5))
d = defaultdict(lst)
,我得到这个错误:
TypeError: first argument must be callable or None
请帮
对于defaultdict
的默认值通常不是一个真正的价值,它工厂:产生一个新的价值的方法。您可以通过使用lambda表达式生成一个列表解决这个问题:
lst = lambda:list(range(0,5))
d = defaultdict(lst)
这也是这里的好主意,因为否则所有默认值将引用相同的列表。比如这里:
d[1].append(14)
将不对d[2]
的影响(假设两者d[1]
和d[2]
不存在)。然而
您可以实现这一有:
val = list(range(0,5))
lst = lambda:val
d = defaultdict(lst)
但是,这可能产生有害的副作用:如果您在此处执行d[1].append(14)
然后d[2]
将[1,2,3,4,5,12]
和d[1] is d[2]
将True
:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> val = list(range(0,5))
>>> lst = lambda:val
>>> d = defaultdict(lst)
>>> d[1]
[0, 1, 2, 3, 4]
>>> d[1].append(14)
>>> d[2]
[0, 1, 2, 3, 4, 14]
>>> d[1] is d[2]
True
而:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> lst = lambda:list(range(0,5))
>>> d = defaultdict(lst)
>>> d[1]
[0, 1, 2, 3, 4]
>>> d[1].append(14)
>>> d[2]
[0, 1, 2, 3, 4]
>>> d[1] is d[2]
False
你应该把参数可以使用lambda
:
from collections import defaultdict
d = defaultdict(lambda: list(range(0,5)))
print(d[0])
# [0, 1, 2, 3, 4]
Default dictionary接受赎回作为第一个参数(这是没有定义的值默认出厂),所以你想要做什么是下一个步骤:
from collections import defaultdict
default_factory = (lambda: list(range(0,5))
d = defaultdict(default_factory)
见What is a "callable" in Python? SO问题更多的调用。
很好的解释。 –
@ Jean-FrançoisFabre:谢谢:) –
所以我不能在现有的列表上使用defaultdict,比如'a = [5,2,3]'? – Arcyno