1.在列表之间移动元素
一个网站有三个未确认的用户需要登录,将其存放在一个列表内。通过while判断该列表非空,在while循环内部做确认处理,将列表底部的元素弹出存放在新的列表内,即可确认用户已经登陆。
示例1.
unconfirmed_users = ['张三' , '李四', '王二']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user:" + current_user.title())
confirmed_users.append(current_user)
print("The following users have been confired:")
for confirmed_user in confirmed_users:
print(confirmed_user)
----------
Result:
Verifying user:王二
Verifying user:李四
Verifying user:张三
The following users have been confired:
王二
李四
张三
2.删除包含特定值的所有列表元素
在前面的章节使用函数remove(),来删除列表中的特定值,只能删除一个列表中的元素。假如列表中有许多相同的元素则可用“while”对此元素做判断,进行逐个删除,直至列表中不再包含指定元素。
示例2.
pets = ['dog', 'cat', 'pig', 'cat']
while 'cat' in pets:
pets.remove('cat')
print(pets)
----------
Result:
['dog', 'pig']
3.使用用户输入来填充字典、
创建一个字典来循环存入,被访用户的姓名和回答。
示例3.
responses = {}
active = True
while active:
name = input("\nWhat is your name? ")
response = input("\n Which sport do you like? ")
responses[name] = response
repeat = input("Do you want anthre person respond? (yes/no)")
if repeat == 'no':
active = False
for name, response in responses.items():
print(name + " would like to play " + response + '.')
----------
Result:
What is your name? 张三
Which sport do you like? 吃鸡
Do you want anthre person respond? (yes/no)no
张三 would like to play 吃鸡.
Process finished with exit code 0