发布时间:2022-04-13 09:50:56 人气:197 作者:多测师
以列表:a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]为说明对象
1.取偶数位置
>>>b = a[::2]
[0, 2, 4, 6, 8]
2.取奇数位置
>>>b = a[1::2]
[1, 3, 5, 7, 9]
3.拷贝整个对象
>>>b = a[:] # ★★★★★
>>>print(b) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>print(id(a)) # 41946376
>>>print(id(b)) # 41921864
>>>b = a.copy()
>>>print(b) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>print(id(a)) # 39783752
>>>print(id(b)) # 39759176
需要注意的是:[:]和.copy()都属于“浅拷贝”,只拷贝最外层元素,内层嵌套元素则通过引用,而不是独立分配内存。
>>>a = [1,2,['A','B']]
>>>print('a={}'.format(a))
a=[1, 2, ['A', 'B']] # 原始a
>>>b = a[:]
>>>b[0] = 9 # 修改b的最外层元素,将1变成9
>>>b[2][0] = 'D' # 修改b的内嵌层元素
>>>print('a={}'.format(a)) # b修改内部元素A为D后,a中的A也变成了D,说明共享内部嵌套元素,但外部元素1没变。
a=[1, 2, ['D', 'B']]
>>>print('b={}'.format(b)) # 修改后的b
b=[9, 2, ['D', 'B']]
>>>print('id(a)={}'.format(id(a)))
id(a)=38669128
>>>print('id(b)={}'.format(id(b)))
id(b)=38669192
4.修改单个元素
>>>a[3] = ['A','B']
[0, 1, 2, ['A', 'B'], 4, 5, 6, 7, 8, 9]
5.在某个位置插入元素
>>>a[3:3] = ['A','B','C']
[0, 1, 2, 'A', 'B', 'C', 3, 4, 5, 6, 7, 8, 9]
>>>a[0:0] = ['A','B']
['A', 'B', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6.替换一部分元素
>>>a[3:6] = ['A','B']
[0, 1, 2, 'A', 'B', 6, 7, 8, 9]
以上内容为大家介绍了Python常用切片操作,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/