【发布时间】:2010-03-24 17:48:11
【问题描述】:
看完What is the best way to implement nested dictionaries?为什么做错了:
c = collections.defaultdict(collections.defaultdict(int))
在python中?我认为这会产生
{key:{key:1}}
还是我想错了?
【问题讨论】:
标签: python collections nested
看完What is the best way to implement nested dictionaries?为什么做错了:
c = collections.defaultdict(collections.defaultdict(int))
在python中?我认为这会产生
{key:{key:1}}
还是我想错了?
【问题讨论】:
标签: python collections nested
defaultdict 的构造函数需要一个可调用对象。 defaultdict(int) 是默认字典对象,而不是可调用对象。但是,使用lambda 可以工作:
c = collections.defaultdict(lambda: collections.defaultdict(int))
这是可行的,因为我传递给外部 defaultdict 的是一个可调用对象,它在调用时会创建一个新的 defaultdict。
这是一个例子:
>>> import collections
>>> c = collections.defaultdict(lambda: collections.defaultdict(int))
>>> c[5][6] += 1
>>> c[5][6]
1
>>> c[0][0]
0
>>>
【讨论】:
Eli Bendersky 为这个问题提供了一个很好的直接答案。将数据重组为
可能会更好>>> import collections
>>> c = collections.defaultdict(int)
>>> c[1, 2] = 'foo'
>>> c[5, 6] = 'bar'
>>> c
defaultdict(<type 'int'>, {(1, 2): 'foo', (5, 6): 'bar'})
取决于你的实际需要。
【讨论】: