美文网首页
Python:使用while循环来处理列表和字典

Python:使用while循环来处理列表和字典

作者: 庭阶 | 来源:发表于2020-04-17 11:55 被阅读0次

for 循环适合以[读]方式遍历列表;while 循环适合以[读写]方式 遍历列表。

1. 在列表之间移动元素

#首先创建一个未确认列表
unconfirmed_users=['alice','brian','candace']
#然后创建一个已确认空列表
confirmed_users=[]
while unconfirmed_users:
    #将未确认列表删除最后一个元素并返回值,赋值给遍历current_user
    current_users=unconfirmed_users.pop()
    print("Verifing user:"
          +current_users.title())
    #将未确认列表删除的元素添加到已确认列表
    confirmed_users.append(current_users)
print("The following users have been comfirmed:")
#打印已确认列表的元素
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
 

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

remove()只是删除列表最先出现的元素,如果列表中有重复的元素,可以用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("\nWhich mountain would you like to climb someday?")
    #将答案存储在字典中,键是name变量,值是response变量
    responses[name]=response
    repeat=input("\n Would you like to let another people respond?(yes/no)")
    if repeat=='no':
        #修改控制循环条件值,为False时结束循环
        polling_active=False
print("\n--Poll resules--")
for name,responses in responses.items():
    print(name+" would like to climb "+responses)

相关文章

网友评论

      本文标题:Python:使用while循环来处理列表和字典

      本文链接:https://www.haomeiwen.com/subject/afbdvhtx.html