栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

0基础学python(22)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

0基础学python(22)

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

我们现在都还只是在处理一小部分数据的时候使用简单的while循环,当我们要记录大量的数据时就需要在while循环中使用字典,列表。

在列表中使用while循环
#首先,创建一个待验证的用户
#   和一个用于储存已验证用户的空列表
uncofirmed_users=['alice','brian','candace']
/confirm/ied_users=[]

#验证每个用户,直到没有未验证的用户为止。
#  将每个经过验证的用户都移到已验证用户列表中。
while un/confirm/ied_users:
	current_user=un/confirm/ied_users.pop()
	print(f"verifying user:{current_user.title()}")
	/confirm/ied_users.append(current_user)
#显示所有已验证的用户。
print("nthe following users have been c/confirm/ied:")
for /confirm/ied_user in /confirm/ied_users:
	print(/confirm/ied_user.title())
verifying user:Candace
verifying user:Brian
verifing user:Alice

the following users have been /confirm/ied:
Candace
Brian
Alice

我们在学删除的时候学到了remove进行指定删除,当我们有一个宠物列表,我们有许多cat元素,我们想要将他删除的时候该怎么输出呢。

pet=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pet)
while 'cat' in pet:
	pet.remove('cat')
	print(pet)

我们发现‘cat’元素在列表中出现了不止一次,使用了while循环,在一次次循环中当发现‘cat’就会进行删除知道没有cat可以删除就会推出循环打印列表。

['dog','cat','dog','goldfish','cat','rabbit','cat']
['dog',,'dog','goldfish',,'rabbit',]
使用用户输出来填充字典
responses={}
#设置一个标志,指出调查是否继续
polling_active=Ture

while polling_active:
#提示输出被调查者的名字和回答。
name=input("nwhat is your name?")
response=input("which mountain would you like to climb someday?")
#将回答储存在字典中。
response[name]=response
#看看是否还有人要参与调查。
repeat=input("would you like to let another person respond(yes/no)")
if repeat =='no':
	polling_active=Flase
#调查结束,显示结果
print("n---poll results---")
for name,response in responses.items():
	print(f"{name}would like to climb {response}.")

我们定义了一个空字典,并设置了一个标志,用于指出调查是否继续,只要只要是ture就运行while。循环中提示输入其名字和想要爬哪座山,将这些信息储存在字典里然后询问用户是否还要继续yes or no。来决定是否继续循环。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/323544.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号