4-10 切片 :选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
打印消息 “The first three items in the list are:” ,再使用切片来打印列表的前三个元素。
打印消息 “Three items from the middle of the list are:” ,再使用切片来打印列表中间的三个元素。
打印消息 “The last three items in the list are:” ,再使用切片来打印列表末尾的三个元素。
players = ['charles', 'allen', 'michael', 'kobe', 'wade']
print("The first three items in the list are:")
print(players[:3])
print("\nThree items from the middle of the list are:")
print(players[1:4])
print("\nThe last three items in the list are:")
print(players[-3:])
结果:
The first three items in the list are:
['charles', 'allen', 'michael']
Three items from the middle of the list are:
['allen', 'michael', 'kobe']
The last three items in the list are:
['michael', 'kobe', 'wade']
4-11 你的比萨和我的比萨 :在你为完成练习 4-1 而编写的程序中,创建比萨列表的副本,并将其存储到变量 friend_pizzas 中,再完成如下任务。
在原来的比萨列表中添加一种比萨。
在列表 friend_pizzas 中添加另一种比萨。
核实你有两个不同的列表。为此,打印消息 “My favorite pizzas are:” ,再使用一个 for 循环来打印第一个列表;打印消息 “My friend's favorite pizzas are:” ,再使用一
个 for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。
my_pizzas = ["Papa John's", "Domino's", "pizza hut"]
friend_pizzas = my_pizzas[:]
my_pizzas.append("McDonald's")
friend_pizzas.append("KFC")
print("My favorite pizzas are:")
for pizza in my_pizzas[:]:
print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas[:]:
print(pizza)
结果:
My favorite pizzas are:
Papa John's
Domino's
pizza hut
McDonald's
My friend's favorite pizzas are:
Papa John's
Domino's
pizza hut
KFC
4-12 使用多个循环 :在本节中,为节省篇幅,程序 foods.py 的每个版本都没有使用 for 循环来打印列表。请选择一个版本的 foods.py ,在其中编写两个 for 循环,将各
个食品列表都打印出来。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
for food in my_foods[:]:
print(food)
print("\nMy friend's favorite foods are:")
for food in friend_foods[:]:
print(food)
结果:
My favorite foods are:
pizza
falafel
carrot cake
cannoli
My friend's favorite foods are:
pizza
falafel
carrot cake
ice cream
4-13 自助餐 :有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。
使用一个 for 循环将该餐馆提供的五种食品都打印出来。
尝试修改其中的一个元素,核实 Python 确实会拒绝你这样做。
餐馆调整了菜单,替换了它提供的其中两种食品。请编写一个这样的代码块:给元组变量赋值,并使用一个 for 循环将新元组的每个元素都打印出来。
foods = ('noodles', 'dumplings', 'hamburger', 'bread', 'chicken')
print('\nOriginal foods:')
for food in foods:
print(food)
foods = ('McFlurry', 'popcorn', 'hamburger', 'bread', 'chicken')
print('\nModified foods:')
for food in foods:
print(food)
结果:
Original foods:
noodles
dumplings
hamburger
bread
chicken
Modified foods:
McFlurry
popcorn
hamburger
bread
chicken