for 循環(huán)適合以[讀]方式遍歷列表;while 循環(huán)適合以[讀寫]方式 遍歷列表。
1. 在列表之間移動元素
#首先創(chuàng)建一個未確認列表
unconfirmed_users=['alice','brian','candace']
#然后創(chuàng)建一個已確認空列表
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()只是刪除列表最先出現(xiàn)的元素,如果列表中有重復的元素惊豺,可以用while 循環(huán)刪除列表的元素
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':
#修改控制循環(huán)條件值尸昧,為False時結束循環(huán)
polling_active=False
print("\n--Poll resules--")
for name,responses in responses.items():
print(name+" would like to climb "+responses)