为什么Python不会为此抛出错误? [英] Why doesn't Python throw an error for this?

查看:85
本文介绍了为什么Python不会为此抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

文件(列表):

ijs的切片被定义为具有 索引k,这样i <= k < j.如果ij大于len(s),请使用 len(s).如果省略iNone,请使用0.如果省略jNone,请使用 len(s).如果i大于或等于j,则切片为空.

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, 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屋!

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