列表的 defaultdict 等效项
问题描述
有没有你如何构建一个相当于 python 的非常有用的 collections.defaultdict
?
Is thereHow would you build an equivalent of python's very useful collections.defaultdict
?
这样一个容器的想象用法:
Imagined usage of such a container:
>>> a = collections.defaultlist(0)
>>> a[2]=7
>>> a[4]='x'
>>> a
[0,0,7,0,'x']
更新:我添加了一个跟进问题a> 为这个结构添加更多功能
UPDATE: I've added a follow up question to add even more functionality to this construct
解决方案
我觉得这样用起来会有点混乱;但是,这是我对如何做到这一点的第一个想法:
I think this would be a bit confusing to use; however, here's my first thought on how to do it:
class defaultlist(list):
def __init__(self, fx):
self._fx = fx
def __setitem__(self, index, value):
while len(self) <= index:
self.append(self._fx())
list.__setitem__(self, index, value)
这需要一个可调用的(我认为 defaultdict 就是这样工作的)作为默认值.
This takes a callable (I think that's how defaultdict works) for the default value.
当我跑步时:
a = defaultlist(int)
print a
a[2] = 7
a[4] = 'x'
print a
我回来了:
[]
[0, 0, 7, 0, 'x']
相关文章