# 切片 L = [‘Michael‘, ‘Sarah‘, ‘Tracy‘, ‘Bob‘, ‘Jack‘] # 用循环取前3个元素 r = [] n = 3 for i in range(n): r.append(L[i]) print(‘get pre 3 elements from L by loop:‘, r) # 对这种经常取指定索引范围的操作,用循环十分繁琐,因此,Python提供了Slice操作符,简化这种操作 # 用Slice取前3个元素 print(‘get pre 3 elements form L by Slice:‘, L[0:3], L[:3]) # 倒数切片 # 倒数第一个元素的索引是-1 print(L[-2:-1], L[-3:]) # 使用[:]复制一个list l = L[:] print(‘copy list L to l, the l is:‘, l) # 对tuple切片 # 切片的结果是tuple T = (0, 1, 2, 3, 4, 5, 6, 7, 8) t = T[:3] print(‘Slice the tuple T to tuple t, the t is:‘, t) # 对str切片 # 切片的结果是str S = ‘ABCDEFG‘ s1 = S[:3] s2 = S[::2] print(s1, s2)
原文地址:http://11317783.blog.51cto.com/11307783/1953393