gpt4 book ai didi

python - 列表类列表

转载 作者:行者123 更新时间:2023-11-28 21:15:44 24 4
gpt4 key购买 nike

我想创建自己的 List of Lists 类。我希望它在其中一个索引为负数时抛出列表索引超出范围错误。

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__? .但我无法让它工作。

最佳答案

外部列表是您的自定义类的列表。但是,每个内部列表都是标准 list 类的列表。为每个列表使用自定义类,它应该可以工作。

例如:

x = MyList([MyList([1,2,3]), MyList([4,5,6]), MyList([7,8,9])])

关于python - 列表类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com