for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则会导致python难以跟踪其中的元素。要遍历列表的同时对其进行修改,可使用while循环。
1、在列表之间移动元素
#helloword.py
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
while unconfirmed_users: #当列表不为空
current_user=unconfirmed_users.pop()
print("Verifying user:"+current_user.title())
confirmed_users.append(current_user)
print("\nThe follwing users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
输出为:
D:\www>python helloword.py
Verifying user:Candace
Verifying user:Brian
Verifying user:Alice
The follwing users have been confirmed:
Candace
Brian
Alice
2、删除包含特定值得所有列表元素
假设有一个宠物列表,其中包含多个值为cat的元素,要删除所有包含cat的元素
#helloword.py
pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
输出为:
D:\www>python helloword.py
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
3、使用用户输入来填充字典
#helloword.py
responses={}
polling_active=True
while polling_active:
name=input("\nwhat is your name?")
response=input("which mountain would you like to climb someday?")
responses[name]=response
repeat=input("would you like to let another person respond?(yes/no)")
if repeat=='no':
polling_active=False
print("\n--Poll results---")
for name,response in responses.items():
print(name+" would like to climb "+response+".")
输出为:
D:\www>python helloword.py
what is your name?jin
which mountain would you like to climb someday?zhu
would you like to let another person respond?(yes/no)yes
what is your name?han
which mountain would you like to climb someday?mu
would you like to let another person respond?(yes/no)no
--Poll results---
jin would like to climb zhu.
han would like to climb mu.