
切片指的是列表的一部分。
1 基本用法
指定第一个元素和最后一个元素的索引,即可创建切片 。Python 会在到达指定的第二个索引之前元素后停止 。
books=['半生缘','往事并不如烟','心是孤独的猎手']
print(books[0:2])
运行结果:

2 未指定索引
如果没有指定第一个索引, 那么 Python 会默认从表头开始:
books=['半生缘','往事并不如烟','心是孤独的猎手']
print(books[:2])
运行结果:

同样,如果没有指定最后一个索引, 那么就会默认从表尾开始:
books=['半生缘','往事并不如烟','心是孤独的猎手']
print(books[1:])
运行结果:

3 负数索引
负数索引会返回离列表末尾相应距离的元素,所以我们可以利用它,来获取列表末尾切片。
books=['半生缘','往事并不如烟','心是孤独的猎手']
print(books[-2:])
运行结果:

4 遍历
可以在 for 循环中使用切片哦O(∩_∩)O~
books=['半生缘','往事并不如烟','心是孤独的猎手']
for book in books[1:]:
print(book)
运行结果:

网友评论