【问题标题】:Why python's list slicing doesn't produce index out of bound error? [duplicate]为什么python的列表切片不会产生索引越界错误? [复制]
【发布时间】:2014-05-21 23:30:54
【问题描述】:

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

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

产生输出:

''
abcde

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

【问题讨论】:

    标签: python string list python-2.7 slice


    【解决方案1】:

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

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

    IndexError: list index out of range
    

    被抛出。

    切片时,如果起始索引大于等于序列长度,则返回序列长度设置为0,在此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,则返回空字符串,在this line

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

    【讨论】:

      【解决方案2】:

      这就是切片操作符在python中的实现方式。如果数组索引超出范围,它将在正确的位置自动截断。

      【讨论】:

        猜你喜欢
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-27
        • 2020-04-23
        相关资源
        最近更新 更多