1.在列表中移动元素
例 假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?
一种办法是使用一个while 循环,在验证用户的同时 将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中
unconfrimed_users={'alice','brian','candance'}
confirmed_users=[]
while unconfrimed_users:
current_user=unconfrimed_users.pop()
print('Verifying user: '+current_user.title())
confirmed_users.append(current_user)
print('\n The following users have been confirmed:')
for user in confirmed_users:
print(user.title())
运行结果:
2.删除包含特定值的所有列表元素
假设你有一个宠物列表,其中包含多个值为’cat’ 的元素。要删除所有这些元素,可不断运行一个while 循环,直到列表中不再包含值’cat’ ,如下所示:
pets=['cat','bird','cat','dog','goldfish']
while 'cat' in pets:
pets.remove('cat')
print(pets)
当元素cat在列表时,执行remove()语句。
于是有多山个cat就执行多少次删除语句
最后得到一个没有cat元素的列表
[‘bird’, ‘dog’, ‘goldfish’]
3.使用用户输入来填充字典
调查问卷。询问用户姓名和想去的山,再询问用户是否愿意邀请另外的人参加问卷调查。如果回复no 就退出循环。
answers={}
flag=True
while flag:
name=input('\nWhat is your name?')
answer=input('Which monuntain would u like to go ?')
answers[name]=answer
repeat=input('Would u like to let another person respond?(yes/no)')
if repeat=='no':
flag=False
print('------------Result-----------')
for name,answer in answers.items():
print(name+' wpuld like to go to: '+answer)
运行结果:
练习
1.熟食店 :创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches 的空列表。遍历列 表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders=['tuna','sweet','tomato','apple']
finished_sandwichs=[]
for i in sandwich_orders:
print('i made your '+i+" sandwich")
san=sandwich_orders.pop()
finished_sandwichs.append(san)
for sandwich in finished_sandwichs:
print(sandwich)
运行结果:
2.五香烟熏牛肉卖完了 :使用为完成练习7-8而创建的列表sandwich_orders ,并确保’pastrami’ 在其中至少出现了三次。在程序开头附近添加 这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while 循环将列表sandwich_orders 中的’pastrami’ 都删除。确认最终的列 表finished_sandwiches 中不包含’pastrami’ 。
sandwich_orders=['tuna','pastrami','pastrami','sweet','tomato','apple','pastrami']
print('we have run out of pastrami sandwichs')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
3.梦想的度假胜地 :编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查 结果的代码块
answers={}
flag=True
while flag==True:
name=input('\nWhat is your name ?')
answer=input("Where would u travel to ?")
answers[name]=answer
reply=input('would u ask your friend to take this test? (yes/no)')
if reply=='no':
flag=False
for key,value in answers.items():
print(key+' would like to go to '+value)
运行结果: