Python 切片索引越界(数组下标越界)

前言

Python语言处理字符串、数组类的问题时有一定概率需要使用切片方法,比如:Leetcode_5
学习官方解法时发现切片的索引可以超出字符串或数组最大索引值,此时编译器不会报错。
欢迎大佬留言说明这种情况的具体原因,本文只进行一些情况的简单测试。

实例代码
a = '123'
b = a[:5]
print(b)

发现结果为123,编译器没有报错。而当直接使用a[5]时即报错string index out of range。下面是测试结果。

测试代码(字符串)
a = "1234567890"
a1 = a[:]
a2 = a[:len(a)]
a3 = a[:15]
a4 = a[16:16]
a5 = a[:2]

运行结果:

This is the id of 'a' :  2707772994160
This is the type of 'a' :  <class 'str'>
This is the value of 'a' :  1234567890

This is the id of 'a1' :  2707772994160
This is the type of 'a1' :  <class 'str'>
This is the value of 'a1' :  1234567890

This is the id of 'a2' :  2707772994160
This is the type of 'a2' :  <class 'str'>
This is the value of 'a2' :  1234567890

This is the id of 'a3' :  2707772994160
This is the type of 'a3' :  <class 'str'>
This is the value of 'a3' :  1234567890

This is the id of 'a4' :  2707740774832
This is the type of 'a4' :  <class 'str'>
This is the value of 'a4' :  

This is the id of 'a5' :  2707773122544
This is the type of 'a5' :  <class 'str'>
This is the value of 'a5' :  12

值得注意的地方:

  1. 若切片后结果与原来相同,则新字符串所指向的物理地址就是原字符串的物理地址(a1、a2、a3)
  2. 若切片后结果与原来不同,则新字符串指向新的物理地址(a5)
  3. 若当前切片索引范围内不存在合法数值,则返回相应类型的空值(a4)
测试代码(数组)
b = [1, 2, 3, 4, 5]
b1 = b[:]
b2 = b[:len(b)]
b3 = b[:15]
b4 = b[16:16]
b5 = b[:2]
This is the id of 'b' :  2260784433096
This is the type of 'b' :  <class 'list'>
This is the value of 'b' :  [1, 2, 3, 4, 5]

This is the id of 'b1' :  2260784432456
This is the type of 'b1' :  <class 'list'>
This is the value of 'b1' :  [1, 2, 3, 4, 5]

This is the id of 'b2' :  2260784470920
This is the type of 'b2' :  <class 'list'>
This is the value of 'b2' :  [1, 2, 3, 4, 5]

This is the id of 'b3' :  2260784534280
This is the type of 'b3' :  <class 'list'>
This is the value of 'b3' :  [1, 2, 3, 4, 5]

This is the id of 'b4' :  2260784471432
This is the type of 'b4' :  <class 'list'>
This is the value of 'b4' :  []

This is the id of 'b5' :  2260784231944
This is the type of 'b5' :  <class 'list'>
This is the value of 'b5' :  [1, 2]

值得注意的地方:

  1. 数组切片操作必定指向新的物理地址。
  2. 若当前切片索引范围内不存在合法数值,则返回相应类型的空值(b4)
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值