切片索引被静默截断,落入允许的范围
因此,无论使用IndexErrors
或start
个参数,切片列表时都不会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
?
答案 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