0基础学python(22)

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

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

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

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

the following users have been confirmed:
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。来决定是否继续循环。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

the best b

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值