这里介绍Python中slice切片的高级用法
命名切片
slice切片是Python的内置类,可通过slice()函数来创建切片对象。用法如下所示
1 2 3 4 5 6 7 8
| s1 = slice(end)
s2 = slice(start, end)
s2 = slice(start, end, step)
|
特别地:
- start、step如果未显式指定,默认为None
- 如果 start 为 None,则从0开始
- 如果 step 为 None,步长为1;
- 如果 end 为 None, 则会包含最后一个位置的元素
1 2 3 4 5 6 7 8 9 10 11 12 13
| print("-------------命名切片----------------------------") stu_tuple_1 = ("Aaron", "Man", "四年级", "一班", 66,77,88) stu_tuple_2 = ("Bob", "female", "二年级", "三班", 60,70)
student_info_slice = slice(2)
class_info_slice = slice(2,4)
score_info_slice = slice(4,None)
print(f"stu1 -> student: {stu_tuple_1[student_info_slice]}, class: {stu_tuple_1[class_info_slice]}, score: {stu_tuple_1[score_info_slice]}") print(f"stu2 -> student: {stu_tuple_2[student_info_slice]}, class: {stu_tuple_2[class_info_slice]}, score: {stu_tuple_2[score_info_slice]}")
|
切片位于赋值语句左侧
事实上,切片还可以位于赋值语句左侧。实现对原数据容器的修改、嫁接、切除等操作
修改
1 2 3 4 5
| list1 = list(range(10)) print(f"list 1: {list1}") list1[2:5] = [20,30,40] print(f"list 1: {list1}")
|
嫁接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| list2 = list(range(5)) print(f"list 2: {list2}") list2[5:] = [555,666,777] print(f"list 2: {list2}")
print("-----------------------------------")
list3 = list(range(5)) print(f"list 3: {list3}")
list3[2:5] = [1000] print(f"list 3: {list3}") list3[1:1] = [-1,-2,-3] print(f"list 3: {list3}")
|
切除
1 2 3 4 5 6 7
| list4 = list(range(8)) print(f"list 4: {list4}") del list4[0:3] print(f"list 4: {list4}") list4[-2:] = [] print(f"list 4: {list4}")
|
参考文献
- Python编程·第3版:从入门到实践 Eric Matthes著
- Python基础教程·第3版 Magnus Lie Hetland著
- 流畅的Python·第1版 Luciano Ramalho著