问题遇到的现象和发生背景
题目要求:
已知受邀请人名单如下:
names = ['li hua', 'zhao si', 'ma hu', 'liu wei', 'yu jin', 'fang hui', 'da yu', 'ma kai', 'hu jie']
请使用pop()不断地删除受邀请人名单,直到只有‘zhao si’和‘ma hu’两位为止,对于被删除的人请告诉他们下次一起共进晚餐,而对于zhao si和ma hu告诉他们仍在受邀请之列。
问题相关代码,请勿粘贴截图
names = ['li hua', 'zhao si', 'ma hu', 'liu wei', 'yu jin', 'fang hui', 'da yu', 'ma kai', 'hu jie']
for name in names:
if name == 'zhao si':
print(f"Dear {name}, you are still invited!")
elif name == 'ma hu':
print(f"Dear {name}, you are still invited!")
else:
uninvited_name = names.pop()
print(f"Sorry {uninvited_name}, let's have dinner next time!")
# 为什么除了'zhao si'和'ma hu'还有其他人在名单之中?
print(names)
运行结果及报错内容
Sorry hu jie, let's have dinner next time!
Dear zhao si, you are still invited!
Dear ma hu, you are still invited!
Sorry ma kai, let's have dinner next time!
Sorry da yu, let's have dinner next time!
Sorry fang hui, let's have dinner next time!
['li hua', 'zhao si', 'ma hu', 'liu wei', 'yu jin']
我的解答思路和尝试过的方法
使用for循环遍历列表,如果名字是'zhao si'或者'ma hu'就输出一句话,其他的则删除列表并致歉。
我想要达到的结果
列表中只剩'zhao si'和'ma hu'