列表列表 Class
List of List Class
我想创建自己的列表 class。我希望它在其中一个索引为负数时抛出列表索引超出范围错误。
class MyList(list):
def __getitem__(self, index):
if index < 0:
raise IndexError("list index out of range")
return super(MyList, self).__getitem__(index)
示例:
x = MyList([[1,2,3],[4,5,6],[7,8,9]])
x[-1][0] # list index of of range -- Good
x[-1][-1] # list index out of range -- Good
x[0][-1] # returns 3 -- Bad
我该如何解决这个问题?我研究了可能的解决方案,例如:Possible to use more than one argument on __getitem__?。但是我无法让它工作。
外部列表是您自定义的列表class。但是,每个内部列表都是标准的列表 list
class。为每个列表使用自定义 class,它应该可以工作。
例如:
x = MyList([MyList([1,2,3]), MyList([4,5,6]), MyList([7,8,9])])
我想创建自己的列表 class。我希望它在其中一个索引为负数时抛出列表索引超出范围错误。
class MyList(list):
def __getitem__(self, index):
if index < 0:
raise IndexError("list index out of range")
return super(MyList, self).__getitem__(index)
示例:
x = MyList([[1,2,3],[4,5,6],[7,8,9]])
x[-1][0] # list index of of range -- Good
x[-1][-1] # list index out of range -- Good
x[0][-1] # returns 3 -- Bad
我该如何解决这个问题?我研究了可能的解决方案,例如:Possible to use more than one argument on __getitem__?。但是我无法让它工作。
外部列表是您自定义的列表class。但是,每个内部列表都是标准的列表 list
class。为每个列表使用自定义 class,它应该可以工作。
例如:
x = MyList([MyList([1,2,3]), MyList([4,5,6]), MyList([7,8,9])])