当切片索引超出范围时,如何引发IndexError? [英] How to raise an IndexError when slice indices are out of range?

查看:430
本文介绍了当切片索引超出范围时,如何引发IndexError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python文档指出


切片索引被静默截断,落入允许范围

因此切片列表时没有 IndexErrors 上升,无论 start stop 参数:

and therefor no IndexErrors are risen when slicing a list, regardless what start or stop parameters are used:

>>> egg = [1, "foo", list()]
>>> egg[5:10]
[]

由于列表 egg 不包含任何大于 2 的索引, egg [5] egg [10] 调用会引发 IndexError

Since the list egg does not contain any indices greater then 2, a egg[5] or egg[10] call would raise an IndexError:

>> egg[5]
Traceback (most recent call last):
IndexError: list index out of range

现在的问题是,当给定的切片索引超出范围时,我们如何提出 IndexError

The question is now, how can we raise an IndexError, when both given slice indices are out of range?

推荐答案

在Python 2中,您可以通过这种方式覆盖 __ getslice __ 方法:

In Python 2 you can override __getslice__ method by this way:

class MyList(list):
    def __getslice__(self, i, j):
        len_ = len(self)
        if i > len_ or j > len_:
            raise IndexError('list index out of range')
        return super(MyList, self).__getslice__(i, j)

然后使用您的班级而不是列表

Then use your class instead of list:

>>> egg = [1, "foo", list()]
>>> egg = MyList(egg)
>>> egg[5:10]
Traceback (most recent call last):
IndexError: list index out of range

这篇关于当切片索引超出范围时,如何引发IndexError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆