首页 > 解决方案 > 带有 Numpy 数组的 Python 中的 IndexError

问题描述

我有以下代码不断给我一个IndexError,我根本不明白为什么:

mainMenu = np.array(['Load new data', 
                 'Check for data errors', 
                 'Generate plots', 
                 'Display list of grades', 
                 'Quit'])

if choice == 2 or choice == 3 or choice == 4:
    print("Please load data before you {:s}".format(mainMenu[choice-1]))
    continue

最后一部分是给出错误的原因:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

谁能看到这里有什么问题?

标签: pythonpython-3.xnumpy

解决方案


嗨,当您定义choice变量时,它似乎不是整数。例如,它被声明为choice = 4.0而不是choice=4 我建议进行以下更改

 if choice == 2 or choice == 3 or choice == 4:
       print("Please load data before you {:s}".format(mainMenu[int(choice)-1]))
continue

推荐阅读