Python入门习题大全——索引
随意创建一个列表,在末尾添加几行代码,以完成如下任务。
打印消息“The first three items in the list ate:”,再使用切片来打印列表的前三个元素。
打印消息“Three items from the middle of the list ate:”,再使用切片来打印列中间的三个元素。
打印消息“The last three items in the list ate:”,再使用切片来打印列表的末尾的三个元素。
# 切片
num = ['a', 'b', 'c', 'd', 'e']
print("The first three items in the list are:")
print(num[:3])
print("Three items from the middle of the list are:")
print(num[1:4])
print("The last three items in the list are:")
print(num[-3:])
输出为:
The first three items in the list are:
['a', 'b', 'c']
Three items from the middle of the list are:
['b', 'c', 'd']
The last three items in the list are:
['c', 'd', 'e']