python - while循环(二)
使用while处理列表和字典
1. 在列表之间移动元素
在for循环遍历列表时,若修改列表元素会导致Python难以跟踪元素。
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
for unconfirmed_user in unconfirmed_users:
unconfirmed_users.remove(unconfirmed_user)
print(f"Verifying user: {unconfirmed_user.title()}")
confirmed_users.append(unconfirmed_user)
print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
输出以下:(发现缺少'brian'元素)
Verifying user: Alice
Verifying user: Candace
The following users have been confirmed:
Alice
Candace
要在遍历列表的同时对列表进行修改,可使用while循环。修改for循环为while循环,将正确输出所有元素。
unconfirmed_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 confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
2. 删除列表中特定值的所有元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
for 'cat' in pets: # 按第一反应是,遍历pets中的所有'cat'
pets.remove('cat')
print(pets)
运行后报错。修改为while循环:
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("Which mountain would you like to climb someday? ")
# 将回答存储在字典中
responses[name] = response
# 看看是否还有人要参与调查
repeat = input("Would you like to let another person response? (yes/ no) ")
if repeat == 'no':
polling_active = False
# 调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name.title()} would like to climb {response}.")
分类:
python
标签:
编程语言/python
, while
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
2022-07-08 datax增量同步