li = [1, 4, 5, 6, 7, 9, 11, 14, 16] # 以下写法都可以表示整个列表,其中 X >= len(li) li[0:X] == li[0:] == li[:X] == li[:] == li[::] == li[-X:X] == li[-X:] li[1:5] == [4,5,6,7] # 从1起,取5-1位元素 li[1:5:2] == [4,6] # 从1起,取5-1位元素,按2间隔过滤 li[-1:] == [16] # 取倒数第一个元素 li[-4:-2] == [9, 11] # 从倒数第四起,取-2-(-4)=2位元素 li[:-2] == li[-len(li):-2] == [1,4,5,6,7,9,11] # 从头开始,取-2-(-len(li))=7位元素 # 步长为负数时,列表先翻转,再截取 li[::-1] == [16,14,11,9,7,6,5,4,1] # 翻转整个列表 li[::-2] == [16,11,7,5,1] # 翻转整个列表,再按2间隔过滤 li[:-5:-1] == [16,14,11,9] # 翻转整个列表,取-5-(-len(li))=4位元素 li[:-5:-3] == [16,9] # 翻转整个列表,取-5-(-len(li))=4位元素,再按3间隔过滤 # 切片的步长不可以为0 li[::0] # 报错(ValueError: slice step cannot be zero)
li = [1, 2, 3, 4] ls = li[::] li == ls # True id(li) == id(ls) # False li.append(li[2:4]) # [1, 2, 3, 4, [3, 4]] ls.extend(ls[2:4]) # [1, 2, 3, 4, 3, 4] # 下例等价于判断li长度是否大于8 if(li[8:]): print("not empty") else: print("empty") # 切片列表受制于原列表 lo = [1,[1,1],2,3] lp = lo[:2] # [1, [1, 1]] lo[1].append(1) # [1, [1, 1, 1], 2, 3] lp # [1, [1, 1, 1]]
li = [1, 2, 3, 4] # 在头部拼接 li[:0] = [0] # [0, 1, 2, 3, 4] # 在末尾拼接 li[len(li):] = [5,7] # [0, 1, 2, 3, 4, 5, 7] # 在中部拼接 li[6:6] = [6] # [0, 1, 2, 3, 4, 5, 6, 7] # 给切片赋值的必须是可迭代对象 li[-1:-1] = 6 # (报错,TypeError: can only assign an iterable) li[:0] = (9,) # [9, 0, 1, 2, 3, 4, 5, 6, 7] li[:0] = range(3) # [0, 1, 2, 9, 0, 1, 2, 3, 4, 5, 6, 7]
li = [1, 2, 3, 4] # 不同位置的替换 li[:3] = [7,8,9] # [7, 8, 9, 4] li[3:] = [5,6,7] # [7, 8, 9, 5, 6, 7] li[2:4] = ['a','b'] # [7, 8, 'a', 'b', 6, 7] # 非等长替换 li[2:4] = [1,2,3,4] # [7, 8, 1, 2, 3, 4, 6, 7] li[2:6] = ['a'] # [7, 8, 'a', 6, 7] # 删除元素 del li[2:3] # [7, 8, 6, 7]
li = [1, 2, 3, 4, 5, 6] li[::2] = ['a','b','c'] # ['a', 2, 'b', 4, 'c', 6] li[::2] = [0]*3 # [0, 2, 0, 4, 0, 6] li[::2] = ['w'] # 报错,attempt to assign sequence of size 1 to extended slice of size 3 del li[::2] # [2, 4, 6]