使用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。来决定是否继续循环。