7.3 使用while循环处理列表和字典
到目前为止,我们每次都只处理了一项用户信息:获取用户的输入,再将输入打印出来或做出应答;循环再次运行时,获悉另一个输入值并做出响应。然而,要记录大量的用户和信息,需要在while循环中使用列表和字典。
for循环是一种遍历列表的有效方式,但不应在for 循环中修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
7.3.1 在列表之间移动元素
假设有一个列表包含新注册但还未验证的网站用户。验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一种办法是使用一个while 循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中。代码可能类似于下面这样:
confirmed_users.py
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表。
unconfirmed_users = ['alice', 'brian', 'candace'] ❶
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止。
# 将每个经过验证的用户都移到已验证用户列表中。
while unconfirmed_users: ❷
current_user = unconfirmed_users.pop() ❸
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user) ❹
# 显示所有已验证的用户。
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
首先创建一个未验证用户列表(见❶),其中包含用户Alice、Brian和Candace,还创建了一个空列表,用于存储已验证的用户。❷处的while 循环将不断运行,直到列表unconfirmed_users 变成空的。在此循环中,❸处的方法pop() 以每次一个的方式从列表unconfirmed_users 末尾删除未验证的用户。由于Candace位于列表unconfirmed_users 末尾,其名字将首先被删除、赋给变量current_user 并加入列表confirmed_users 中(见❹)。接下来是Brian,然后是Alice。
为模拟用户验证过程,我们打印一条验证消息并将用户加入已验证用户列表中。未验证用户列表越来越短,而已验证用户列表越来越长。未验证用户列表为空后结束循环,再打印已验证用户列表:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
7.3.2 删除为特定值的所有列表元素
在第3章中,我们使用函数remove() 来删除列表中的特定值。这之所以可行,是因为要删除的值只在列表中出现一次。如果要删除列表中所有为特定值的元素,该怎么办呢?
假设你有一个宠物列表,其中包含多个值为'cat' 的元素。要删除所有这些元素, 可不断运行一个while循环,直到列表中不再包含值'cat' ,如下所示:
pets.py
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
首先创建一个列表,其中包含多个值为'cat' 的元素。打印这个列表后,Python进入while循环,因为它发现'cat' 在列表中至少出现了一次。进入该循环后, Python删除第一个'cat' 并返回到while 代码行,然后发现'cat' 还包含在列表中,因此再次进入循环。它不断删除'cat' ,直到这个值不再包含在列表中,然后退出循环并再次打印列表:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
7.3.3 使用用户输入来填充字典
可使用while 循环提示用户输入任意多的信息。下面创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:
mountain_poll.py
responses = {}
# 设置一个标志,指出调查是否继续。
polling_active = True
while polling_active:
# 提示输入被调查者的名字和回答。
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ") ❶
# 将回答存储在字典中。
responses[name] = response ❷
# 看看是否还有人要参与调查。
repeat = input("Would you like to let another person respond? (yes/ no) ") ❸
if repeat == 'no':
polling_active = False
# 调查结束,显示结果。
print("\n--- Poll Results ---")❹
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
这个程序首先定义了一个空字典(responses ),并设置了一个标志(polling_active )用于指出调查是否继续。只要polling_active 为True,Python就运行while 循环中的代码。
在这个循环中,提示用户输入其名字及其喜欢爬哪座山(见❶)。将这些信息存储在 字典responses 中(见❷),然后询问用户是否继续调查(见❸)。如果用户输入yes ,程序将再次进入while 循环;如果用户输入no ,标志polling_active 将被设置为False ,而while 循环将就此结束。最后一个代码块(见❹)显示调查结果。
如果运行这个程序,并输入一些名字和回答,输出将类似于下面这样:
What is your name? Sun
Which mountain would you like to climb someday? xiaozhushan
Would you like to let another person respond? (yes/ no) yes
What is your name? Liu
Which mountain would you like to climb someday? dazhushan
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Sun would like to climb xiaozhushan.
Liu would like to climb dazhushan.
动手试一试
练习7-8:熟食店
创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名字,再创建一个名为finished_sandwiches 的空列表。遍历列表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 中。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['包子','馅饼','油条']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
finished_sandwiches.append(current_sandwich)
print(f"我做了{current_sandwich}。")
print("所有三明治都做好了。分别是:")
for sandwich in finished_sandwiches:
print(sandwich)
练习7-9:五香烟熏牛肉卖完了
使用为完成练习7-8而创建的列表sandwich_orders ,并确保'pastrami' 在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉(pastrami)卖完了;再使用一个while循环将列表sandwich_orders 中的'pastrami' 都删除。确认最终的列表finished_sandwiches 未包含'pastrami' 。
sandwich_orders = ['包子','馅饼','油条','包子','豆浆','包子']
print(sandwich_orders)
print("包子已经卖完了。只剩下:")
while '包子' in sandwich_orders:
sandwich_orders.remove("包子")
print(sandwich_orders)
练习7-10:梦想的度假胜地
编写一个程序,调查用户梦想的度假胜地。使用类似于下面的提示,并编写一个打印调查结果的代码块。
If you could visit one place in the world, where would you go?
reports = {}
active = True
while active:
name = input("请输入姓名:")
place = input("请输入想去的度假胜地:")
reports[name] = place
repeat = input("是否要继续参与?(是/否)")
if repeat == "否":
active = False
print("--- 统计结果 ---")
for name,place in reports.items():
print(f"{name}想去{place}旅游。")
7.4 小结
在本章中,你学习了:
如何在程序中使用input() 来让用户提供信息;
如何处理文本和数的输入,以及如何使用while 循环让程序按用户的要求不断运行;
多种控制while 循环流程的方式:设置活动标志、使用break 语句以及使用continue 语句;
如何使用while 循环在列表之间移动元素,以及如何从列表中删除所有包含特定值的元素;
如何结合使用while 循环和字典。