简体   繁体   English

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

[英]Python Force List Index out of Range Exception

I have a list of lists 我有一份清单清单

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

I want the code to throw an Array Out of Bounds Exception similar to how is does in Java when the index is out of range. 我希望代码抛出一个Array Out of Bounds Exception,类似于Java在索引超出范围时的情况。 For example, 例如,

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

If an exception is thrown, I want it to return 0. 如果抛出异常,我希望它返回0。

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

I think basically anytime the index is negative, throw an exception. 我认为基本上任何时候索引都是负数,抛出异常。

You can create your own list class, inheriting the default one, and implementing the __getitem__ method that returns the element in a specified index: 您可以创建自己的列表类,继承默认列表类,并实现返回指定索引中元素的__getitem__方法:

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

Example: 例:

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

There is a better way to handle the border cases: just increase the array by two in both dimensions and fill all border with a default (eg 0) and never update them. 有一种更好的方法来处理边界情况:只需在两个维度中将数组增加2并用默认值填充所有边界(例如0)并且永远不会更新它们。 For neighbourhood and update, just search the inner field (index 1..(len-2)), instead of 0..len-1. 对于邻域和更新,只需搜索内部字段(索引1 ..(len-2)),而不是0..len-1。 So, the indexes will never be out of bounds for the neighbourhood search. 因此,索引永远不会超出邻域搜索范围。 This elliminates the need for special treatment. 这消除了对特殊治疗的需要。 (I did this many years ago for the same usage, but in a different language - Pascal, iirc.) (多年前我这样做是为了相同的用法,但用不同的语言--Pascal,iirc。)

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

This will eventually raise an index error, as len(any_list) is always +1 past the last valid index. 这最终会引发索引错误,因为len(any_list)总是比最后一个有效索引+1。 Btw. 顺便说一句。 it is good advise only to catch expected exceptions (the ones you actually want to handle); 建议只捕捉预期的异常(你真正想要处理的异常); your code will catch any exception. 你的代码会捕获任何异常。

Ok, just read your comment. 好的,请阅读您的评论。 Your original question sounded as if you wanted to provoke an index error. 您的原始问题听起来好像是要引发索引错误。

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

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