[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> print(squares[0:3])
[1, 4, 9]
如果你没有指定第一个索引,Python将自动从列表开头开始
>>> print(squares[:3])
[1, 4, 9]
要让切片终止于列表末尾,可使用类似的语法
>>> print(squares[2:])
[9, 16, 25, 36, 49, 64, 81, 100]
*负数索引还可以返回离列表末尾相应距离的元素,你可以输出列表末尾的任何切片
>>> print(squares[-3:])
[64, 81, 100]
遍历切片
#helloword.py
numbers=range(1,10)
for number in numbers[:3]:
print(number)
输出为:
D:\www>python helloword.py
1
2
3
eg:
#helloword.py
my_foods=['egg','banana','cake']
friend_foods=my_foods[:]
my_foods.append('apple')
print('my favorite foods are:')
print(my_foods)
friend_foods.append('pizza')
print('friend favorite foods are:')
print(friend_foods)
输出为:
D:\www>python helloword.py
my favorite foods are:
['egg', 'banana', 'cake', 'apple']
friend favorite foods are:
['egg', 'banana', 'cake', 'pizza']
*倘若我们只是简单的将my_foods赋值给friend_foods,将不能得到两个列表
#helloword.py
my_foods=['egg','banana','cake']
friend_foods=my_foods
my_foods.append('apple')
print('my favorite foods are:')
print(my_foods)
friend_foods.append('pizza')
print('friend favorite foods are:')
print(friend_foods)
输出结果为:
D:\www>python helloword.py
my favorite foods are:
['egg', 'banana', 'cake', 'apple']
friend favorite foods are:
['egg', 'banana', 'cake', 'apple', 'pizza']