约 2007 字
约 10 分钟
切片是对元组和列表中部分元素创建的视图,有以下写法:
tuple_or_list[:] # 所有元素的切片
tuple_or_list[start:] # 从 索引start 到 最后一个元素 的切片
tuple_or_list[:stop] # 从 索引0 到 索引stop 的切片,不含 索引stop
tuple_or_list[start:stop] # 从 索引start 到 索引stop 的切片,不含 索引stop
tuple_or_list[start:stop:step] # 从 索引start 到 索引stop 的切片,不含 索引stop,步长为 step
例如:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[:])
print(numbers[5:])
print(numbers[:3])
print(numbers[1:4])
print(numbers[2:7:3])
Loading...
切片是对源列表的引用,因此修改切片的元素等同于修改源列表的元素:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[2:7] = [233] # 将 索引2 到 索引7,不含 索引7 替换为 [233]
print(numbers)
Loading...
元组是不可变类型,因此不能通过切片进行修改。
字符串也支持切片操作:
text:str = "hello world"
print(text[4:7])
Loading...
字符串是不可变类型,因此不能通过切片进行修改。
如果将切片赋值给一个变量,该变量会基于此切片创建新的实体,而不是引用源列表:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shadow:list[int] = numbers[2:7] # 将 索引2 到 索引7,不含 索引7 赋值给变量 shadow,将创建新的列表
shadow[1] = 233 # 修改 shadow 元素的值,不会影响 numbers
print(shadow)
print(numbers)
Loading...
因此可以通过切片简化列表的复制操作:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shadow:list[int] = numbers[:] # 复制 numbers
# shadow:list[int] = list(numbers) # 等价
创建于 2025/4/11 03:41:55
更新于 2025/4/11 03:41:55