You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表按用户输入索引执行pop操作问题求助

问题分析与解决代码
  • 核心错误:你在循环遍历列表时用了for guests in guests:,这会把原本存储列表的guests变量彻底覆盖——循环结束后,guests不再是列表,而是列表里的最后一个字符串元素,自然没法调用列表的pop()方法。

  • 修正后的完整代码:

# First list of classmates
guests = ['ngqika', 'anissa', 'melina', 'robert', 'marcus', 'rob', 'keagon', 'william', 'jason', 'raven']

# 排序后遍历,用不同变量名避免覆盖原列表
guests.sort()   
for guest in guests:
    print(guest.title())

# 输出作业要求的提示语句
print("\nOops! It turns out one of your guests can't make it.")

# 获取用户输入的索引
guest_index = int(input('Please enter the index number of the guest to be deleted from the list: '))

# 按索引移除嘉宾并获取被移除的姓名
popped_guest = guests.pop(guest_index)

# 输出包含嘉宾姓名的确认信息
print(f"Confirmed: {popped_guest.title()} has been removed from the guest list.")
  • 关键修正点说明:
    • 循环变量改用guest而非guests,保留原列表的引用。
    • 替换提示语为作业要求的标准内容。
    • 调用pop()时必须用圆括号(你之前试的大括号{}是语法错误,仅字典才用大括号),传入输入的索引即可。
    • 利用pop()返回的被删除元素,直接生成确认提示。

内容的提问来源于stack exchange,提问作者Stacy Earl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:03:15