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

如何通过起始为1的枚举索引删除列表元素?代码报错求助

问题解决:通过枚举索引删除列表元素的错误修复

错误原因

你代码里的del grocery_list[int(which_item-1)]会报错,核心问题是input()获取的which_item是字符串类型,直接对字符串做减法which_item-1不符合Python语法规则,会触发TypeError。

修正后的代码

把目标行改成先将输入转为整数,再执行减1操作(匹配列表的0起始索引):

if main == 'remove':
    for count, item in enumerate(grocery_list, 1):
        print(f'{count}. {item}')
    # 提示文字建议和操作匹配,避免用户混淆
    which_item = input('Which item do you want to remove? Type in the index number please! ')
    del grocery_list[int(which_item) - 1]
    print('Your item has been removed! ')
    continue

额外优化(可选)

为避免用户输入非数字内容或超出范围的索引导致程序崩溃,可以增加输入验证:

if main == 'remove':
    for count, item in enumerate(grocery_list, 1):
        print(f'{count}. {item}')
    while True:
        which_item = input('Which item do you want to remove? Type in the index number please! ')
        if which_item.isdigit():
            index = int(which_item) - 1
            if 0 <= index < len(grocery_list):
                del grocery_list[index]
                print('Your item has been removed! ')
                break
            else:
                print(f'Invalid index! Please enter a number between 1 and {len(grocery_list)}.')
        else:
            print('Please enter a valid number!')
    continue

内容的提问来源于stack exchange,提问作者auyona cooper

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:19:54