Python class that works as list of lists

我的梦境 提交于 2019-12-13 09:54:35

问题


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?

EDIT: 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.


回答1:


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]


来源:https://stackoverflow.com/questions/47732330/python-class-that-works-as-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!