Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当切片索引超出范围时,如何提高索引器?_Python_Exception_Indexing_Slice - Fatal编程技术网

Python 当切片索引超出范围时,如何提高索引器?

Python 当切片索引超出范围时,如何提高索引器?,python,exception,indexing,slice,Python,Exception,Indexing,Slice,国家 切片索引被自动截断,以在允许的范围内 因此,在对列表进行切片时,无论使用什么开始或停止参数,都不会出现索引器: >>> egg = [1, "foo", list()] >>> egg[5:10] [] 由于列表egg不包含任何大于2的索引,因此egg[5]或egg[10]调用将引发索引器: >> egg[5] Traceback (most recent call last): IndexError: list index out of

国家

切片索引被自动截断,以在允许的范围内

因此,在对列表进行切片时,无论使用什么
开始
停止
参数,都不会出现
索引器

>>> egg = [1, "foo", list()]
>>> egg[5:10]
[]
由于列表
egg
不包含任何大于
2
的索引,因此
egg[5]
egg[10]
调用将引发
索引器

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

现在的问题是,当两个给定的切片索引都超出范围时,我们如何提出一个索引器?

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

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()
def切片超出界限(顺序,开始=无,结束=无,步骤=1):
长度=长度(序列)
如果“开始”为“无”:
如果步长>1,则开始=0,否则长度
如果开始<0:
开始=长度-开始
如果结束为无:
结束=步长>1时的长度,否则为0
如果end<0:
结束=长度-结束

如果不是(0在Python 2中,您可以通过以下方式重写
\uuuu getslice\uuuu
方法:

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)
然后使用您的类而不是
列表

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

为什么不可以?因为空切片结果仍然是有效对象。如果要引发异常,请手动探测开始索引和结束索引,或者根据您的边界显式测试
len(egg)
。@MartijnPieters:谢谢您的答复!我不确定这是否重复,因为我询问了“切片序列时如何引发索引器”,而不是“为什么切片索引超出范围”。如果我错了,请纠正我:)你问了两个问题,使你的文章过于宽泛。我骗你回答了前面的一个问题,回答了第一个问题,并为你提供了回答第二个问题的选项。@MartijnPieters:好的,我知道了,我有一个编辑过的问题……那么什么时候应该提出例外?当两个索引都超出范围时?对于任何导致空白切片的索引,应该怎么做d出现负指数?对于起点>=终点且步幅不为负的切片?请更具体地说明您希望引发错误的原因,因为您可能会将不同的场景视为错误。