Slicing 使用语法 sequence[start:stop:step] 从序列(list、tuple、string)中提取一部分。这是 Python 中一个强大、简洁的特性,经常被使用。
基本 slicing
python
nums = [0, 1, , , , ]
nums[:]
nums[:]
nums[:]
nums[:]
关键规则:start 包括,stop 排除 (nums[1:4] 给出索引 1、2、3 — 而不是 4)。
nums[-1] # 5 — last element
nums[-2] # 4 — second to last
nums[-3:] # [3, 4, 5] — last three elements
nums[:-1] # [0, 1, 2, 3, 4] — everything except the last
nums[::2] # [0, 2, 4] — every 2nd element
nums[1::2] # [1, 3, 5] — every 2nd, starting at index 1
nums[::-1] # [5, 4, 3, 2, 1, 0] — REVERSE the sequence (a famous idiom)
nums[::-1] 反转序列是最容易识别的 Python 习语之一。
s = "Hello"
s[1:4] # "ell"
s[::-1] # "olleH" — reverse a string
s[0] # "H"
nums = [0, 1, 2, 3, 4]
nums[1:3] = [10, 20, 30] # replace a slice (can change length)
# nums → [0, 10, 20, 30, 3, 4]
nums[10:20] # [] — out-of-range slices return empty, don't crash (unlike nums[10])
与单个索引访问(会引发 IndexError)不同,slicing 优雅地返回可用的内容。
Slicing 是一个无处不在、独特的 Python 特性,用于清洁地提取、复制和反转序列。
理解 start:stop:step 语法(尤其是包括起始/排除停止)、负索引(从末尾计数)、反转习语 ([::-1]) 以及 slicing 是安全的(在范围外不会崩溃)使您能够简洁、正确地操作列表和字符串。
它替代了常见操作的冗长循环,并在习惯用法的 Python 代码中随处可见。