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