python

python(13):使用while循环处理列表和字典

2022-04-07  本文已影响0人  Z_bioinfo

1.在列表之间移动元素

假设有一个列表,其中包含新注册但还未验证的网站用户:验证这些用户后,如何将他们移动到另一个已验证用户列表中呢?一种办法时使用while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其假如到另一个已验证用户列表中

unconfirmed_users = ['alice', 'daming', 'tom']#创建一个待验证用户列表
confirmed_users = []#用于存贮已验证用户的空列表
#验证每个用户,直到没有未验证用户为止
#将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print('verifying users :' + current_user)
    confirmed_users.append(current_user)
#显示所有已验证的用户
print('\nthe following users have been confirmed:')
for confirmed_user in confirmed_users:
    print(confirmed_user)
verifying users :tom
verifying users :daming
verifying users :alice

the following users have been confirmed:
tom
daming
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']

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

创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答,将手机的数据存贮再一个字典中,以便将回答同被调查者关联起来

responses = {}#定义一个空字典
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
    #提示输入被调查者的名字和回答
    name = input('\nwhat is your name')
    reponse = input('which mountain would you like to climb someday')
    
    #将答卷存贮在字典中
    responses[name] = reponse
    
    #看看是否还有人要参与调查
    repeat = input('\would you like to let another person resond(yes/no)')
    if repeat == 'no':
        polling_active = False

#调查结束,显示结果
print('\n---poll results---')
for name,response in responses.items():
    print(name + ' would you like to climb' + response + '.')
what is your namexm
which mountain would you like to climb somedayximalaya
\would you like to let another person resond(yes/no)no

---poll results---
xm would you like to climbximalaya.
上一篇下一篇

猜你喜欢

热点阅读