ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-01-16 15:04:30  阅读:216  来源: 互联网

标签:confirmed users name cat 7.3 while user print 字典


1.在列表之间移动元素

 

#首先创建一个待验证用户列表

#再创建一个用于存储已验证用户的空列表
unconfirmed_users=['alice','brian','tom']
confirmed_users=[]


#验证每个用户,将每个经过验证的元素都移到已验证用户列表中

#pop()函数每次从列表unconfirmed_users末尾删除一个的用户
#title() 方法返回"标题化"的字符串,单词以大写开始,其余字母均为小写
#append() 方法用于在列表末尾添加新的对象


while unconfirmed_users:
    curent_user=unconfirmed_users.pop()
    print("Verifying user:"+curent_user.title())
    confirmed_users.append(curent_user)




#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

 运行结果:

>>> 
================ RESTART: D:\python学习\7.3\confirmed_users.py ================
Verifying user:Tom
Verifying user:Brian
Verifying user:Alice

The following users have been confirmed:
Tom
Brian
Alice
>>> 

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

 

#删除列表中所有包含特定值的元素
pets=['dog','cat','dog','goldfish','cat','rabbit','cat']

print(pets)

while 'cat' in pets:
    pets.remove('cat')

print()
print(pets)

 

 运行结果:

====================== RESTART: D:/python学习/7.3/pets.py ======================
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']

['dog', 'dog', 'goldfish', 'rabbit']
>>> 

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

 

#使用用户输入来填充字典
#每次循环提示输入被调查者的名字和回答,收集的数据存放在一个字典中

responses={}
polling_active=True

while polling_active:
    
    name=input("\nWhat's your name?")
    response=input("Which mountain would you like to climb someday?")
    responses[name]=response#将答案填充到字典中
    repeat=input("Y/N?")#设置一个标志,决定是否继续
    if repeat=='N':
        polling_active=False

print("\n===========Poll Results========== ")    #调查结束,显示结果
for name,response in responses.items():
    print(name+" would like to climb "+response+'.')     

'''
注意:
1.填充字典的方法
2.字典输出的方法

'''

 运行结果:

>>> 
====================== RESTART: D:/python学习/7.3/填充字典.py ======================

What's your name?张三
Which mountain would you like to climb someday?泰山
Y/N?Y

What's your name?Tom
Which mountain would you like to climb someday?Alps
Y/N?N

===========Poll Results========== 
Tom would like to climb Alps.
张三 would like to climb 泰山.
>>> 

 

标签:confirmed,users,name,cat,7.3,while,user,print,字典
来源: https://www.cnblogs.com/ylzchs/p/14285519.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有