python - while循环(二)

发布时间 2023-07-08 20:52:08作者: 钱塘江畔

使用while处理列表和字典

1. 在列表之间移动元素

在for循环遍历列表时,若修改列表元素会导致Python难以跟踪元素。

unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

for unconfirmed_user in unconfirmed_users:
    unconfirmed_users.remove(unconfirmed_user)
    print(f"Verifying user: {unconfirmed_user.title()}")
    confirmed_users.append(unconfirmed_user)

print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

输出以下:(发现缺少'brian'元素)

Verifying user: Alice
Verifying user: Candace

The following users have been confirmed: 
Alice
Candace

要在遍历列表的同时对列表进行修改,可使用while循环。修改for循环为while循环,将正确输出所有元素。

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())

2. 删除列表中特定值的所有元素

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

for 'cat' in pets:      # 按第一反应是,遍历pets中的所有'cat'
    pets.remove('cat')
    
print(pets)

运行后报错。修改为while循环:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
    
print(pets)

3. 使用用户输入来填充字典

# 构造空字典
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 response? (yes/ no) ")
    if repeat == 'no':
        polling_active = False
    
# 调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(f"{name.title()} would like to climb {response}.")