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

Python列表索引TypeError报错解析及用户选择列表元素实现方案

解决列表索引类型错误问题

问题原因

你代码里用了str(input("Write your option:")),把用户输入的内容强制转换成了字符串类型。哪怕用户输入的是数字1,choice1存储的也是字符串"1",而Python列表的索引必须是整数或切片,不能是字符串,所以list1[choice1]会抛出TypeError: list indices must be integers or slices, not str。而直接写list1[1]时,1是整数类型,符合索引规则,所以能正常输出。

可行方案

基础修正版

把输入转换成整数类型即可:

list1 = ["unity1", "unity2", "unity3"]
choice1 = int(input("Write your option:")) # 用户输入1
print("Your choice is ", list1[choice1])

进阶验证版

如果要避免用户输入非数字或超出列表范围的情况,可以添加异常处理和范围检查:

list1 = ["unity1", "unity2", "unity3"]
try:
    choice1 = int(input("Write your option:"))
    # 检查输入的索引是否在列表有效范围内
    if 0 <= choice1 < len(list1):
        print("Your choice is ", list1[choice1])
    else:
        print(f"请输入0到{len(list1)-1}之间的数字")
except ValueError:
    # 处理用户输入非整数的情况
    print("请输入有效的整数")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:20:50