在python中创建默认列表 [英] creating a defaultlist in python

查看:97
本文介绍了在python中创建默认列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为非常有用的 collections.defaultdict 创建一个等效列表.以下设计效果很好:

I'm trying to create a list equivalent for the very useful collections.defaultdict. The following design works nicely:

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)

使用方法如下:

>>> dl = defaultlist(lambda:'A')
>>> dl[2]='B'
>>> dl[4]='C'
>>> dl
['A', 'A', 'B', 'A', 'C']

我应该在默认列表中添加些什么,以支持以下行为?

What should I add to the defaultlist so as to support the following behavior?

>>> dl = defaultlist(dict)
>>> dl[2]['a'] = 1
>>> dl
[{}, {}, {'a':1}]

推荐答案

在给出的示例中,您首先尝试检索列表中不存在的值,就像执行dl[2]['a']一样,Python首先检索第三个(索引2)元素,然后继续在该对象上获取名为'a'的元素-因此,您还必须实现对__getitem__方法的自动扩展行为,如下所示:

On the example you give, you first try to retrieve a non-existing value on the list, as you do dl[2]['a'], Python first retrieve the third (index 2) element on the list, then proceed to get the element named 'a' on that object - therefore you have to implement your automatic extending behavior to the __getitem__ method as well, like this:

class defaultlist(list):
    def __init__(self, fx):
        self._fx = fx
    def _fill(self, index):
        while len(self) <= index:
            self.append(self._fx())
    def __setitem__(self, index, value):
        self._fill(index)
        list.__setitem__(self, index, value)
    def __getitem__(self, index):
        self._fill(index)
        return list.__getitem__(self, index)

这篇关于在python中创建默认列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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