彻底理解Python list切片原理
本文深入解析Python中list的insert函数及切片机制。详细阐述切片参数beg、end、delta的默认值与处理逻辑,区分正负步长下的边界行为。通过代码示例展示切片作为副本的特性,并重点剖析切片赋值与删除操作的内部预处理规则,帮助开发者避免常见越界错误。
list.insert函数处理逻辑
关于list的insert函数
list.insert(index, value)方法用于在指定索引index对应的元素之前插入新值value。
首先对参数index进行预处理:如果index小于0,则执行index += len(list),将其转换为正数下标。
经过预处理之后,
若处理后的index仍小于0,则将其设为0,相当于在列表头部插入;若index大于列表长度len(list),则将其设为len(list),相当于在列表尾部插入。
Python列表切片基础原理
切片实例
Python中的列表切片功能非常灵活,使用者需要透过表象分析其内在机理,这样才能熟练运用。
下标支持负数具有两面性:好处是使用起来更加简便,坏处是当下标越界时可能不会报错,反而引发难以察觉的错误。
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取
切片参数默认值规则
由此可见,列表切片涉及三个关键参数:beg(起始下标)、end(终止下标)和delta(变化量/步长)。
- 当delta小于0时,beg的默认值为len(array)-1,end的默认值为开头之前(即-1对应的逻辑位置)。
- 当delta大于0时,beg的默认值为0,end的默认值为最末之后(即len(array))。
- 当delta未给出时,delta默认为1。
以下代码示例演示了大致原理:学习一项技术,应先了解其表象,再分析内在实现,最后查阅源代码仔细推敲其具体实现方式。
需要注意的是,列表切片操作产生的是原列表的一个副本,与原列表不共享同一块内存空间。
x=[1,2,3]
y=x[:]
x[0]=-1
print(y) #输出[1,2,3]
列表切片写操作详解
列表切片写操作
接下来探究切片的写操作机制。
>>> x=[1,2,3,4,5]
>>> x[2:0]=100 #在2后面插入若干个元素,应该用列表
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
>>> x[2:0]=[100]
>>> x
[1, 2, 100, 3, 4, 5]
>>> del x[2:3] #删除切片
>>> x
[1, 2, 3, 4, 5]
>>> x[2:1]=[100] #对于切片x[from:to],会进行预处理to=max(from+1,to)
>>> x
[1, 2, 100, 3, 4, 5]
>>> del x[2:0] #对于切片del操作,如果from>to,不执行任何操作
>>> x
[1, 2, 100, 3, 4, 5]
>>> del x[2:1]
>>> x
[1, 2, 100, 3, 4, 5]
>>> del x[2:3]
>>> x
[1, 2, 3, 4, 5]
>>> x[2:4]=None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
>>> x[2:4]=[None]
>>> x
[1, 2, None, 5]
对列表切片进行更深入的理解:
def between(beg, end, mid):
# 判断mid是否位于begin和end之间
return end > mid >= beg or end < mid <= beg
def get_slice(a, beg, end, delta=1):
# 数组切片get方式
if delta == 0: raise ValueError("slice step cannot be 0")
# 将负数下标转化一下
if beg < 0: beg += len(a)
if end < 0: end += len(a)
# 如果转化完成之后依然不在合法范围内,则返回空列表
if beg < 0 and end < 0 or beg >= len(a) and end >= len(a): return []
# 如果方向不同,则返回空列表
if (end - beg) * delta <= 0: return []
# 将越界的部分进行裁剪
beg = max(0, min(beg, len(a) - 1))
end = max(-1, min(end, len(a)))
ans = []
i = beg
while between(beg, end, i):
ans.append(a[i])
i += delta
return ans
def set_slice(a, li, beg, end, delta=1):
if delta == 0: raise ValueError("slice step cannot be 0")
if delta == 1:
# 如果delta==1,那么li的长度可以随意
if beg < 0: beg += len(a)
if end < 0: end += len(a)
beg = max(0, min(beg, len(a) - 1))
end = max(-1, min(end, len(a)))
for i in range(beg, end):
del a[beg]
for i in reversed(li):
a.insert(beg, i)
else:
# delta!=1,相当于替换
if len(get_slice(a, beg, end, delta)) != len(li): raise ValueError("array don't match")
if len(li) == 0: return
if beg < 0: beg += len(a)
if end < 0: end += len(a)
beg = max(0, min(beg, len(a) - 1))
# 用li中的全部元素逐一替换
for ind, value in enumerate(li):
a[ind * delta + beg] = value
def test_getSlice():
a = list(range(10))
import random
for i in range(10):
beg = random.randint(-15, 15)
end = random.randint(-15, 15)
delta = 0
while delta == 0: delta = random.randint(-15, 15)
print(len(get_slice(a, beg, end, delta)) == len(a[beg:end:delta]), beg, end, delta)
def test_setSlice():
import random
for i in range(10):
a = list(range(10))
beg = random.randint(-15, 15)
end = random.randint(-15, 15)
delta = 0
while delta == 0: delta = random.randint(-5, 5)
sz = len(a[beg:end:delta])
if delta == 1: sz = random.randint(0, 4)
li = [random.randint(0, 100) for i in range(sz)]
set_slice(a, li, beg, end, delta)
mine = a
a = list(range(10))
a[beg:end:delta] = li
print(a == mine)
test_setSlice()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













