设为首页 加入收藏

TOP

使用while循环来处理列表和字典——参考Python编程从入门到实践
2019-06-24 22:06:05 】 浏览:38
Tags:使用 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 + '.')

运行结果:

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python-numpy-pandas 下一篇python算法与数据结构-希尔排序(3..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目