Python 与字典比较时,列表索引超出范围
我正试图在Python3.7中使用字典变量和输入创建一个菜单系统,新的编码人员只是摸不着头脑 我试图在varchoice中保存用户选择,然后使用choices与擦洗输入进行比较,但是当运行代码时,代码始终失败Python 与字典比较时,列表索引超出范围,python,python-3.x,Python,Python 3.x,我正试图在Python3.7中使用字典变量和输入创建一个菜单系统,新的编码人员只是摸不着头脑 我试图在varchoice中保存用户选择,然后使用choices与擦洗输入进行比较,但是当运行代码时,代码始终失败 Traceback (most recent call last): File "D:\Nu Voute De Merde\[Redact]\Python Creations\[Redact]\code.py", line 32, in <module>
Traceback (most recent call last):
File "D:\Nu Voute De Merde\[Redact]\Python Creations\[Redact]\code.py", line 32, in <module>
if choice == choices[5]:
IndexError: list index out of range
在大多数编程语言中,数组是
0索引的
so
choices = [1, 2, 3, 4, 5]
print(choices[0]) # 1
print(choices[4]) # 5
print(choices[5]) # IndexError
dict的改进
- 不需要将输入转换为
,直接将输入的字符串与数组中的字符串进行比较int
- 最好直接使用dictionary属性,以检查键的存在,这样可以避免对相同的内容多次写入
- 您可以使用dict内容在
输入中构建命题
列表的改进 当您使用数字作为键时,您甚至可以将您的选择存储在一个数组中
menu = ["Add New Address",
"Change Existing Address",
"View All Addresses Where Last Name Starts With Letter",
"List All Addresses",
"Quit"]
choice = int(input("\n".join(f"{idx + 1}.{ch}"
for idx, ch in enumerate(menu)) + "\nChoice: "))
if choice > 4:
print(menu[4])
exit()
else:
print(menu[choice - 1])
值得注意的是,这不同于
菜单
,这是一本您自己设置键(这里是数字1-5)的字典。非常感谢!你刚刚释放了我的周末,从我的网站上删除了10行code@E.V.A.不客气,我已经添加了一个解决方案,使用列表而不是dict,只是为了让您知道。如果答案对你有帮助,请毫不犹豫地接受它;)用你自己的话来说,你为什么期望选择[5]
是有效的?你期望的结果是什么?用你自己的话来说:dict
的目的是什么?与使用其他容器相比,它能为您提供的主要优势是什么?您如何在代码中利用这一点?
## Creates the menu using dict vars
menu = {'1': "Add New Address",
'2': "Change Existing Address",
'3': "View All Addresses Where Last Name Starts With Letter",
'4': "List All Addresses",
'5': "Quit"}
# Takes the input from the user
choice = input("\n".join('.'.join(pair) for pair in menu.items()) + "\nChoice: ")
if choice == '5' or choice not in menu:
print(menu['5'])
exit()
else:
print(menu[choice])
menu = ["Add New Address",
"Change Existing Address",
"View All Addresses Where Last Name Starts With Letter",
"List All Addresses",
"Quit"]
choice = int(input("\n".join(f"{idx + 1}.{ch}"
for idx, ch in enumerate(menu)) + "\nChoice: "))
if choice > 4:
print(menu[4])
exit()
else:
print(menu[choice - 1])