Python中的自动增长列表?

kjo*_*kjo 9 python list

我需要一个类似列表的对象,只要访问大于或等于其长度的插槽号就会"自动增长",用一些预先指定的默认值填充所有新创建的插槽.例如:

# hypothetical DefaultList class
x = DefaultList(list('abc'), default='*')
x[6] = 'g'
print x[2], x[4], x[6], x[8]  # should print 'c * g *'
Run Code Online (Sandbox Code Playgroud)

谢谢!

PS.我知道实现这样的课程并不困难,但我尽可能避免轮胎改造,特别是如果一个特别有效/精心设计的轮子已经存在的话.

PS2.dict(或collections.defaultdict)不是所需数据结构的可接受实现.为什么,请看这里:http://groups.google.com/group/comp.lang.python/msg/bcf360dfe8e868d1?hl = en

unu*_*tbu 3

class DefaultList(list):
    def __init__(self,*args,**kwargs):
        list.__init__(self,*args)
        self.default=kwargs.get('default',None)
    def __getitem__(self,key):
        # retrieving an item does not expand the list
        if isinstance(key,slice):
            return [self[elt] for elt in range(key.start,key.stop,key.step)]
        else:
            try:
                return list.__getitem__(self,key)
            except IndexError:
                return self.default
    def __setitem__(self,key,value):
        # setting an item may expand the list
        try:
            list.__setitem__(self,key,value)
        except IndexError:
            self.extend([self.default]*(key-len(self)))
            self.append(value)

x = DefaultList(list('abc'), default='*')
print(x)
# ['a', 'b', 'c']
x[6] = 'g'
print(x)
# ['a', 'b', 'c', '*', '*', '*', 'g']
print x[2], x[4], x[6], x[8]  # should print 'c * g *'
# c * g *
print(x[2:9:2])
# ['c', '*', 'g', '*']
Run Code Online (Sandbox Code Playgroud)