列表的 defaultdict 等效项 [英] defaultdict equivalent for lists

查看:45
本文介绍了列表的 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']

这篇关于列表的 defaultdict 等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆