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
相关产品推荐
相关产品推荐

