The Python 文档 https://docs.python.org/2/library/exceptions.html#exceptions.IndexError指出
切片索引被无声地截断掉在允许范围
因此没有IndexErrors
切片列表时会上升,无论什么start
or stop
使用参数:
>>> egg = [1, "foo", list()]
>>> egg[5:10]
[]
自从上榜以来egg
不包含任何大于该值的索引2
, a egg[5]
or egg[10]
调用会引发IndexError
:
>> egg[5]
Traceback (most recent call last):
IndexError: list index out of range
现在的问题是,我们怎样才能筹集到IndexError
,当两个给定的切片索引都超出范围时?
在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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)