使用while循环来处理列表和字典——参考Python编程从入门到实践

2020-12-13 03:33

阅读:430

标签:src   使用   remove   存储   data   设置   info   person   用户输入   

1. 在列表之间移动元素

unconfirmed_users = [alice, brian, candace]
confirmed_users = []
# 验证每个用户,知道没有未验证的用户
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print(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())

运行结果:

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice

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

pets = [dog, cat, dog, goldfish, cat, rabbit, cat]
print(pets)
while cat in pets:
    pets.remove(cat)
print(pets)

运行结果:

[dog, cat, dog, goldfish, cat, rabbit, cat]
[dog, dog, goldfish, rabbit]

若不用while循环,则 pets.remove(cat) 只能移除列表中遇到的第一个 ‘cat‘。

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 respond? (yes / no) )
    if repeat == no:
        polling_active = False
# 调查结束,显示结果
print(\n--- Polling Result ---)
for name, response in responses.items():
    print(name +  would like to climb  + response + .)

运行结果:

技术图片

 

使用while循环来处理列表和字典——参考Python编程从入门到实践

标签:src   使用   remove   存储   data   设置   info   person   用户输入   

原文地址:https://www.cnblogs.com/shirley-yang/p/11079215.html


评论


亲,登录后才可以留言!