Python- 将 While 循环与列表和字典一起使用
处理多个用户输入:
- While 循环可以通过将多个输入存储在列表或字典中来收集和管理它们。
- 与 for 循环不同,while 循环可以在执行过程中修改列表,使其可用于动态管理数据(如用户输入)。
在列表之间移动数据:
可以使用 while 循环将数据从一个列表传输到另一个列表。
在此示例中,我们从未经验证的用户列表和已确认用户的空列表开始。在验证每个用户时,我们使用 while 循环将他们从未验证列表移动到已确认列表。
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
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:
current_user = unconfirmed_users.pop() # Remove the last unverified user
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user) # Add the user to the confirmed list
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
>>
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
- 只要 while 循环不为空unconfirmed_users 就会运行。
- pop() 方法从 unconfirmed_users 中删除最后一个用户并将其分配给 current_user。
- 每个经过验证的用户都使用 append() 添加到 confirmed_users。
- 确认所有用户后,循环结束,程序将打印已确认的用户。
从列表中删除特定值:
要删除特定值的所有实例(例如,从列表中删除所有 'cat' 条目),请使用 while 循环。
假设我们有一个包含特定值的多个实例的列表,例如 'cat',并且我们想要删除所有匹配项。while 循环反复删除 'cat',直到没有剩余。
# List of pets with multiple 'cat' entries
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print("Original list of pets:", pets)
# Remove all instances of 'cat' from the list
while 'cat' in pets:
pets.remove('cat')
print("Updated list of pets:", pets)
>>
Original list of pets: ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
Updated list of pets: ['dog', 'dog', 'goldfish', 'rabbit']
- while 循环检查 pets 列表中是否仍存在 'cat'。
- 如果找到 'cat',它会使用 remove() 删除它的第一个匹配项。
- 循环重复,直到删除 'cat' 的所有实例。
用用户输入填充字典:
while 循环可以收集用户的输入并将其存储在字典中,从而将用户的响应与其姓名相关联。
在此示例中,我们创建一个投票程序,在该程序中向用户提出问题,并将他们的答案存储在字典中。每个用户的名称是键,他们的响应是值。
# Empty dictionary to store responses
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? ")
response = input("Which mountain would you like to climb someday? ")
# Store the response in the dictionary
responses[name] = response
# Ask if another user wants to respond
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat.lower() == 'no':
polling_active = False
# Polling is complete, display the results
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
>>
What is your name? Nidhi
Which mountain would you like to climb someday? Mount Everest
Would you like to let another person respond? (yes/no) yes
What is your name? Nid
Which mountain would you like to climb someday? Eastern Himalaya
Would you like to let another person respond? (yes/no) no
--- Poll Results ---
Nidhi would like to climb Mount Everest.
Nid would like to climb Eastern Himalaya.
- 只要 polling_active 为 True,while 循环就会一直运行。
- 该程序会提示用户输入他们的名字和他们想要攀登的山峰。
- 响应存储在 responses 字典中,其中 key 是用户名,value 是他们的响应。
- 然后,系统会询问用户是否要允许其他人响应。如果他们键入 'no',则循环通过设置 polling_active = False 结束。
- 轮询结束后,程序将打印所有响应。