本文转载自CSDN博主【巨輪】的博文, 原文地址: https://blog.csdn.net/u011863024/article/details/109585500
[:]与 [::] 语法是通用序列操作(Common Sequence Operations)其中的两个。用 [:] 或[::]对多数序列类型(可变的或不可变的)(如字符串、列表等)序列中元素进行截取。
s[i:j]
从下标 i 到下标 j,截取序列 s 中的元素。
>>> a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[-1:]
[9]
>>> a[-9:-1]
[1, 2, 3, 4, 5, 6, 7, 8]
>>> a[1:20]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[0:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[9:3]
[]
>>>
s[i:j:k]
从下标 i 到下标 j,步长为 k,截取序列 s 中的元素。
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[1:10:2]
[1, 3, 5, 7, 9]
>>> a[1:10:3]
[1, 4, 7]
>>> a[1:10:-2]
[]
>>> a[1:10:-3]
[]
>>> a[10:1:-2]
[9, 7, 5, 3]
>>> a[10:1:-3]
[9, 6, 3]
>>> a[::2]
[0, 2, 4, 6, 8]
>>> a[::-2]
[9, 7, 5, 3, 1]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[-9:-1:2]
[1, 3, 5, 7]
>>> a[-9:-1:-2]
[]
>>> a[-1:-9:-2]
[9, 7, 5, 3]
>>> a[-1::-2]
[9, 7, 5, 3, 1]
>>> a[:-1:2]
[0, 2, 4, 6, 8]
>>>