← 中文资源

简体中文版本

切片赋值原地增删改列表

列表切片赋值可以替换区间、用空切片插入、赋空列表删除:被赋的序列长度任意,列表随之伸缩,del items[2:] 一行完成尾部裁剪,全程原地完成。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

['alpha', 'beta2', 'beta3', 'gamma2', 'delta']
['head', 'alpha', 'beta2', 'beta3', 'gamma2', 'delta']
['head', 'alpha', 'gamma2', 'delta']
['head', 'alpha']

实现说明

顶层就这几处状态:items。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 状态都挂在模块顶层:items。

代码示例

# Slice assignment replaces, inserts, or deletes ranges in place;
# the assigned sequence may have any length, so the list resizes
items = ['alpha', 'beta', 'gamma', 'delta']

# Replace two items with three: the list grows by one
items[1:3] = ['beta2', 'beta3', 'gamma2']
print(items)

# An empty slice inserts without removing anything
items[0:0] = ['head']
print(items)

# Assigning nothing to a range deletes it
items[2:4] = []
print(items)

# del with a slice drops everything from the index to the end
del items[2:]
print(items)