为什么Python不会为此抛出错误? [英] Why doesn't Python throw an error for this?
问题描述
MATLAB为此抛出错误:
MATLAB throws an error for this:
>> a = [2,3,4]
>> a(3:4)
index out of bounds
如果使用Python尝试了类似的操作,为什么它不合法?
If something similar is tried with Python, why isn't it illegal?
>>> a = [2,3,4]
>>> a[2:3]
[4]
考虑到Python中的编号从零开始,是不是python中的索引'3'超出了范围?
Isn't the Index '3' in python out of bounds, considering Numbering starts from Zero in Python?
推荐答案
切片永远不会在python中引发索引超出范围的错误.
Slicing never raise error in python for out of bound indexes..
>>> s =[1,2,3]
>>> s[-1000:1000]
[1, 2, 3]
在字符串上的 docs 中(适用于列表,元组为很好):
From the docs on string(applies to lists, tuples as well):
退化的切片索引得到了很好的处理:一个索引也是如此 大由字符串大小代替,上限小于 下限返回一个空字符串.
Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.
文件(列表):
从
i
到j
的s
的切片被定义为具有 索引k
,这样i <= k < j
.如果i
或j
大于len(s)
,请使用len(s)
.如果省略i
或None
,请使用0
.如果省略j
或None
,请使用len(s)
.如果i
大于或等于j
,则切片为空.
The slice of
s
fromi
toj
is defined as the sequence of items with indexk
such thati <= k < j
. Ifi
orj
is greater thanlen(s)
, uselen(s)
. Ifi
is omitted orNone
, use0
. Ifj
is omitted orNone
, uselen(s)
. Ifi
is greater than or equal toj
, the slice is empty.
超出范围的负片索引会被截断,但不要对单元素(非片)索引尝试这样做:
Out-of-range negative slice indices are truncated, but don’t try this for single-element (non-slice) indices:
>>> word = 'HelpA'
>>> word[-100:]
'HelpA'
这篇关于为什么Python不会为此抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!