如果切片索引超出范围,如何引发IndexError?

时间:2015-08-07 09:59:01

标签: python exception indexing slice

Python Documentation表示

  

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

因此,无论使用IndexErrorsstart个参数,切片列表时都不会stop上升:

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

由于列表 egg不包含任何大于2 的索引,因此egg[5]egg[10]调用会引发{{1} }}:

IndexError

现在的问题是,如果两个给定的切片索引超出范围,我们怎样才能提出>> egg[5] Traceback (most recent call last): IndexError: list index out of range

2 个答案:

答案 0 :(得分:1)

这里没有银弹;你必须测试两个边界:

def slice_out_of_bounds(sequence, start=None, end=None, step=1):
    length = len(sequence)
    if start is None:
        start = 0 if step > 1 else length
    if start < 0:
        start = length - start
    if end is None:
        end = length if step > 1 else 0
    if end < 0:
        end = length - end
    if not (0 <= start < length and 0 <= end <= length):
        raise IndexError()

由于切片中的结束值是独占的,因此允许范围最大为length

答案 1 :(得分:1)

在Python 2中,您可以通过以下方式覆盖__getslice__方法:

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)

然后使用您的班级代替list

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