简体   繁体   English

Python 不断为列表抛出“TypeError”错误,我不知道如何修复它

[英]Python keeps throwing a "TypeError" error for a list, and I can't figure out how to fix it

So, I'm kind of new to Python, and I'm trying to make a small command line menu system with lists, using the following code:所以,我对 Python 有点陌生,我正在尝试使用以下代码制作一个带有列表的小型命令行菜单系统:

menu = ["item1", "item2", "item3", "item4"]

i = 0

for item in menu2:
    print(str(i) + str(menu[item]))
    i = i + 1

But whenever I run that code, I'm thrown the following error:但是每当我运行该代码时,都会抛出以下错误:

TypeError: list indices must be integers, not str        

Can anyone tell me why this is happening or how to fix it?谁能告诉我为什么会发生这种情况或如何解决? I've tried most anything I can think of.我已经尝试了大多数我能想到的东西。

Thanks in advance!提前致谢!

remove str also not needed menu.删除 str 也不需要菜单。 print statement should be like below.打印语句应如下所示。

print(i + item)

You can use the range function您可以使用范围功能

You are having a TypeError because menu is a list, not a string.你有一个 TypeError 因为菜单是一个列表,而不是一个字符串。 It wants you to define the index to access the string inside the list.它希望您定义索引以访问列表中的字符串。

menu = ["item1", "item2", "item3", "item4"]


for item in range(len(menu)):
    print(str(item) + str(menu[item]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM