为什么python的列表切片不会产生索引越界错误? [英] Why python's list slicing doesn't produce index out of bound error?

查看:36
本文介绍了为什么python的列表切片不会产生索引越界错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在玩数组切片时,我注意到 a[index:] 或 a[:index] 类型的切片不会产生字符串的数组索引越界错误.

While playing with array slicing I noticed that a[index:] or a[:index] type of slicing doesn't produce array index out of bound error for strings.

str = "abcde"
print str[10:]
print str[:10]

产生输出:

''
abcde

谁能解释一下为什么?它不应该产生数组索引越界错误吗?如果我尝试执行以下操作,Python 确实会产生此错误:print str[10].

Can anybody explain why? Shouldn't it produce array index out of bounds error ? Python does produce this error if I try to do something like : print str[10].

推荐答案

切片用于创建新列表.如果索引不在列表中元素数量的范围内,我们可以返回一个空列表.所以,我们不必抛出错误.

Slicing is used to create a new list. If the indices don't fall within the range of the number of elements in the list, we can return an empty list. So, we don't have to throw an error.

但是,如果我们尝试访问列表中大于元素数量的元素,我们将无法返回任何默认值(甚至None 也不行,因为它可能是列表中的有效值)列表).这就是为什么

But, if we try to access the elements in the list which is greater than the number of elements, we cannot return any default value (not even None because it could be a valid value in the list). That is why

IndexError: list index out of range

被抛出.

切片时,如果起始索引大于等于序列的长度,则返回的序列长度设置为0,在此

While slicing, if the starting index is greater than or equal to the length of the sequence, the length of the returned sequence is set to be 0, in this line

defstop = *step < 0 ? -1 : length;
...
if (r->stop == Py_None) {
    *stop = defstop;
}
...
if ((*step < 0 && *stop >= *start)
    || (*step > 0 && *start >= *stop)) {
    *slicelength = 0;

对于Strings,如果切片后返回的字符串长度为0,则返回一个空字符串,在这一行

For the Strings, if the length of the string to be returned after slicing is 0, then it returns an empty string, in this line

if (slicelength <= 0) {
    return PyString_FromStringAndSize("", 0);
}

这篇关于为什么python的列表切片不会产生索引越界错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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