使用while循环处理列表和字典
到目前为止,我们一次只处理一条用户信息。 我们收到用户的输入,然后打印输入或对它的响应。 下一次通过 while 循环时,我们将收到另一个输入值并对其做出响应。 但是要跟踪许多用户和信息片段,我们需要在 while 循环中使用列表和字典。
for 循环对于遍历列表是有效的,但是你不应该在 for 循环中修改列表,因为 Python 将难以跟踪列表中的项目。 要在处理列表时修改列表,请使用 while 循环。 将 while 循环与列表和字典一起使用可以让您收集、存储和组织大量输入,以便稍后检查和报告。
在列表之间移动元素
考虑一个新注册但未经验证的网站用户列表。 在我们验证这些用户之后,我们如何将他们移动到单独的已确认用户列表中? 一种方法是在我们验证用户时使用 while 循环从未确认用户列表中拉出用户,然后将他们添加到单独的已确认用户列表中。 该代码可能如下所示:
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace'] (1)
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users: (2)
current_user = unconfirmed_users.pop() (3)
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user) (4)
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
1 | 我们从一个未确认用户列表(Alice、Brian 和 Candace)和一个包含已确认用户的空列表开始。 |
2 | 只要列表 unconfirmed_users 不为空,while 循环就会运行。 |
3 | 在这个循环中,pop() 方法从 unconfirmed_users 的末尾一次删除一个未验证的用户。 |
4 | 因为 Candace 在 unconfirmed_users 列表中排在最后,她的名字将首先被删除,分配给 current_user,并添加到 confirmed_users 列表。 接下来是布赖恩,然后是爱丽丝。 |
我们通过打印验证消息来模拟确认每个用户,然后将它们添加到已确认用户列表中。 随着未确认用户列表的缩小,已确认用户列表会增加。 当未确认用户列表为空时,循环停止并打印已确认用户列表:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
删除为特定值的所有列表元素
在第 3 章中,我们使用 remove() 从列表中删除特定值。 remove() 函数起作用是因为我们感兴趣的值在列表中只出现过一次。 但是如果你想从列表中删除一个值的所有实例怎么办?
假设您有一个宠物列表,其值“cat”重复了几次。 要删除该值的所有实例,您可以运行一个 while 循环,直到“cat”不再出现在列表中,如下所示:
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' 的每个实例,直到该值不再出现在列表中,此时 Python 退出循环并再次打印列表:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
使用用户输入填充字典
您可以在每次通过 while 循环时根据需要提示输入尽可能多的输入。 让我们制作一个投票程序,其中每个通过循环提示参与者的姓名和响应。 我们会将收集到的数据存储在字典中,因为我们想将每个响应与特定用户联系起来:
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ") (1)
response = input("Which mountain would you like to climb someday? ")
# Store the response in the dictionary.
responses[name] = response (2)
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond? (yes/ no) ") (3)
if repeat == 'no':
polling_active = False
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items(): (4)
print(f"{name} would like to climb {response}.")
该程序首先定义一个空字典(responses)并设置一个标志(polling_active)以指示轮询处于活动状态。 只要 polling_active 为 True,Python 就会在 while 循环中运行代码。
1 | 在循环中,系统会提示用户输入他们的名字和他们想要攀登的山。 |
2 | 该信息存储在响应字典中, |
3 | 并询问用户是否继续运行投票。 |
4 | 如果他们输入 yes,程序将再次进入 while 循环。 如果他们输入 no,则 polling_active 标志设置为 False,while 循环停止运行,最后的代码块显示轮询结果。 |
如果您运行该程序并输入示例响应,您应该会看到如下输出:
What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes
What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.
总结
在本章中,您学习了如何使用 input() 来允许用户在您的程序中提供他们自己的信息。 您学习了如何处理文本和数字输入,以及如何使用 while 循环让您的程序按照用户的意愿运行。 您看到了几种通过设置活动标志、使用 break 语句和使用 continue 语句来控制 while 循环流程的方法。 您学习了如何使用 while 循环将项目从一个列表移动到另一个列表,以及如何从列表中删除某个值的所有实例。 您还了解了 while 循环如何与字典一起使用。
在第 8 章中,您将了解函数。 函数允许您将程序分成小部分,每个小部分完成一项特定的工作。 您可以根据需要多次调用函数,并且可以将函数存储在单独的文件中。 通过使用函数,您将能够编写更高效的代码,更易于故障排除和维护,并且可以在许多不同的程序中重复使用。