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

Posted shirley-yang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用while循环来处理列表和字典——参考Python编程从入门到实践相关的知识,希望对你有一定的参考价值。

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编程从入门到实践的主要内容,如果未能解决你的问题,请参考以下文章

Python ❀ while循环

Python ❀ while循环

如何在使用while循环时将值附加到字典中的列表?

结束无限的while循环

while循环 操作列表与字典

while循环,布尔类型,可变or不可变,数字,字符串,列表,元组,字典