while循环结合列表或字典
练习一 :在列表之间移动元素
创建一个名为sandwich_orders的列表,其中包含各种三明治的名字,再创建一个名为finished_sandwiches 的空列表。遍历列表sandwich_orders,对于其中的每种三明治,都打印一条消息,如“I made your tuna sandwich.”,并将其移到列表 finished_sandwiches中。当所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['tuna', 'pastrami', 'turkey', 'pastrami', 'club', 'veggie', 'pastrami']
finished_sandwiches = []while sandwich_orders:sandwich_order = sandwich_orders.pop() ## pop()每次是从末尾删除元素print("I made your tuna sandwich")finished_sandwiches.append(sandwich_order) ## append追加到finished_sandwiches## 验证
for sandwich_order in finished_sandwiches:print(sandwich_order)
结果展示
练习二:删除特定值的所有列表元素
使用上道题创建的列表sandwich_orders,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:先打印一条消息,指出熟食店的五香烟熏牛肉(pastrami)卖完了;再使用一个 while 循环将列表 sandwich_orders中的'pastrami'都删除。确认最终的列表finished_sandwiches 中未包含'pastrami"。
sandwich_orders = ['tuna', 'pastrami', 'turkey', 'pastrami', 'club', 'veggie', 'pastrami']
print("pastrami买完了!!!")while "pastrami" in sandwich_orders:sandwich_orders.remove("pastrami")# print(sandwich_orders)
print(sandwich_orders)
python删除第一个pastrami并返回while代码行,然后发现列表中还有pastrami,继续循环,不断删除pastrami,直到列表中没有。
结果展示
练习三:使用用户输入填充字典
编写一个程序,调查用户梦想中的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。
responese = {}polling_active = True ## 设置一个标志,调差结果是否继续
while polling_active:name = input("\nWhat is your name? ")place = input("\nIf you could visit one place in the world, where would you go?")## 将内容存储到字典中responese[name] = placerepect = input("\nWhat is your repect? (yes/no)")if repect == "no":polling_active = Falseprint("---Thanks for playing!----")
for name, place in responese.items():print(f"{name.title()} would love to visit: {place.title()}")
结果展示