Python强制列表索引超出范围异常

coo*_*490 6 python list

我有一份清单清单

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

我希望代码抛出一个Array Out of Bounds Exception,类似于Java在索引超出范围时的情况.例如,

x[0][0]   # 1
x[0][1]   # 2
x[0-1][0-1]  # <--- this returns 9 but I want it to throw an exception
x[0-1][1]    # <--- this returns 7 but again I want it to throw an exception
x[0][2]     # this throws an index out of range exception, as it should
Run Code Online (Sandbox Code Playgroud)

如果抛出异常,我希望它返回0.

try:
    x[0-1][0-1]   # I want this to throw an exception
except:
    print 0       # prints the integer 0
Run Code Online (Sandbox Code Playgroud)

我认为基本上任何时候索引都是负数,抛出异常.

Jun*_*sor 16

您可以创建自己的列表类,继承默认列表类,并实现__getitem__返回指定索引中元素的方法:

class MyList(list):
    def __getitem__(self, index):
        if index < 0:
            raise IndexError("list index out of range")
        return super(MyList, self).__getitem__(index)
Run Code Online (Sandbox Code Playgroud)

例:

>>> l = MyList([1, 2, 3])
>>> l[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __getitem__
IndexError: list index out of range
>>> l[0]
1
>>> l[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __getitem__
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)