繁体   English   中英

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

[英]Python Force List Index out of Range Exception

我有一份清单清单

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

我希望代码抛出一个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

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

try:
    x[0-1][0-1]   # I want this to throw an exception
except:
    print 0       # prints the integer 0

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

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

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

例:

>>> 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

有一种更好的方法来处理边界情况:只需在两个维度中将数组增加2并用默认值填充所有边界(例如0)并且永远不会更新它们。 对于邻域和更新,只需搜索内部字段(索引1 ..(len-2)),而不是0..len-1。 因此,索引永远不会超出邻域搜索范围。 这消除了对特殊治疗的需要。 (多年前我这样做是为了相同的用法,但用不同的语言--Pascal,iirc。)

try:
    x[len(x)][0]
except IndexError:
    ...

这最终会引发索引错误,因为len(any_list)总是比最后一个有效索引+1。 顺便说一句。 建议只捕捉预期的异常(你真正想要处理的异常); 你的代码会捕获任何异常。

好的,请阅读您的评论。 您的原始问题听起来好像是要引发索引错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM