顺着切,反着切,想怎么切就怎么切,但是别被坑。
mylist = [1,2,3,4,5,6,7,8,9] print(mylist[2:7:2]) # [3, 5, 7] print(mylist[:7:2]) # [1, 3, 5, 7] print(mylist[2::2]) # [3, 5, 7, 9] print(mylist[2:9:2]) # [3, 5, 7, 9] print(mylist[2:10:2]) # [3, 5, 7, 9] print(mylist[::2]) # [1, 3, 5, 7, 9] print(mylist[7:2:2]) # [] print(mylist[2:7:-2]) # [] print(mylist[7:2:-2]) # [8, 6, 4] print('============') print(mylist[-2:-7:-2]) # [8, 6, 4] print(mylist[:-7:-2]) # [9, 7, 5] print(mylist[-2::-2]) # [8, 6, 4, 2] print(mylist[-2:-10:-2]) # [8, 6, 4, 2] print(mylist[::-2]) # [9, 7, 5, 3, 1] print(mylist[-7:-2:-2]) # [] print(mylist[-2:-7:2]) # [] print(mylist[-7:-2:2]) # [3, 5, 7]
步长如果是整数,开始要小于结束,否则结果肯定为空
步长如果是负数,开始要大于结束,否则结果肯定为空
# 反转 print(mylist[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1] mylist.reverse() print(mylist) # [9, 8, 7, 6, 5, 4, 3, 2, 1]
左闭右开
print([1,2,3,4,5,6,7,8,9][1:3:]) # [2, 3] print([1,2,3,4,5,6,7,8,9][-1:-7:-1]) # [9, 8, 7, 6, 5, 4]