python笔记 分片slice

list1 = [1,2,3,4,5,6,7]
list1[0:1]     #[1]

list1[:1]       #[1]

lits1[1:]       #[2,3,4,5,6,7,]
1) 之前提到的“简洁”分片操作在这里有效:

  1. >>> list1[::2]
  2. [1, 2, 7]

复制代码


2) 步长不能为0,要不就走不动了:

  1. >>> list1[::0]
  2. Traceback (most recent call last):
  3.   File "<pyshell#11>", line 1, in <module>
  4.     list1[::0]
  5. ValueError: slice step cannot be zero

复制代码


3) 步长可以是负数,改变方向(从尾部开始向左走):

  1. >>> list1[::-2]
  2. [8, 9, 3]

复制代码


4) 步子太大容易扯着蛋......

猜你喜欢

转载自blog.csdn.net/weixin_41948344/article/details/81146189