TypeError: 'type' object is not subscriptable during reading data

TypeError: 'type' object is not subscriptable during reading data

我是导入数据的新手,我正在尝试制作按呈现顺序读取的 def。错误在函数中,而不是在数据中。

def read_eos(filename: str, order: dict[str, int] = {"density": 0, "pressure": 1, 
    "energy_density": 2}):
  
    # Paths to files
    current_dir = os.getcwd()
    INPUT_PATH = os.path.join(current_dir, "input")

    in_eos = np.loadtxt(os.path.join(INPUT_PATH, filename))
    eos = np.zeros(in_eos.shape)

    # Density
    eos[:, 0] = in_eos[:, order["density"]]
    eos[:, 1] = in_eos[:, order["pressure"]]
    eos[:, 2] = in_eos[:, order["energy_density"]]

    return eos

看起来问题出在您的函数参数之一的类型提示中:dict[str, int]。就Python而言,[str, int]是一个下标类型的dict,但是dict不能接受那个下标,因此出现您的错误消息。

修复相当简单。首先,如果您还没有这样做,请在您的函数定义上方添加以下导入语句:

from typing import Dict

然后,将 dict[str, int] 更改为 Dict[str, int]