用作列表列表的Python类 [英] Python class that works as list of lists

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

问题描述

我正在尝试创建一个可以用作列表列表的python类.但是,到目前为止,我所能开发的只是

I'm trying to create a python class that can work as a list of lists. However, all I've managed to develop so far is,

class MyNestedList(list):
...

我知道上面的代码可以工作,

I'm aware that the above code will work as,

my = MyNestedList()
my[0] = 1
...

但是我希望我的班级能像这样

But I want my class to work as,

my[0][0] = 1
...

有人可以请我进一步指导吗?

Will anyone please guide me further?

作为个人,我希望类作为deap框架的类型传递.我无法将列表列表作为类型传递,因为那样会破坏我的结构.

I want the class to pass as a type for the deap framework, as my individual. I can't pass list of lists as my type as it would break my structure.

推荐答案

这里是一个示例.您必须使用足够的元素来初始化嵌套列表,否则会出现索引错误.

Here is an example. You have to initialize the nested list with enough elements, or you'll get index errors.

class NestedLst(object):
    def __init__(self, x, y):
        self.data = [[None]*y]*x

    def __getitem__(self, i):
        return self.data[i]

nlst = NestedLst(2, 2)
nlst[0][0] = 10
print nlst[0][0]

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

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