在Python中自动增长列表 [英] Automatically growing lists in Python

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

问题描述

有没有一种方法可以在Python中建立一个自动增长的列表?我的意思是制作一个列表,该列表在引用不存在的索引时会增长.基本上是Ruby数组的行为.

Is there a way to make an automatically growing list in Python? What I mean is to make a list that would grow when an index that does not yet exist is referenced. Basically the behaviour of Ruby arrays.

提前谢谢!

推荐答案

当然可以,您只需要使用list的子类即可.

Sure it's possible, you just have to use a subclass of list to do it.

class GrowingList(list):
    def __setitem__(self, index, value):
        if index >= len(self):
            self.extend([None]*(index + 1 - len(self)))
        list.__setitem__(self, index, value)

用法:

>>> grow = GrowingList()
>>> grow[10] = 4
>>> len(grow)
11
>>> grow
[None, None, None, None, None, None, None, None, None, None, 4]

这篇关于在Python中自动增长列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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