我想要使用我的脚本输入所独有的配置。e.x。如果类型= veh1,请为veh1等设置配置。我认为解决这个问题的最好方法是使用字典:
veh1 = {
"config_1":1,
"config_2":"a"
}
veh2 = {
"config_1":3,
"config_2":"b"
}
type = "veh1"
print(type["config_1"])我本以为这会打印出1,但是我得到了一个错误,因为python正在尝试分割字符串veh1,而不是调用名为veh1的字典
TypeError: string indices must be integers, not str我尝试过str(type),但没有成功。我可以使用if遍历字典名称来设置配置,但这样做会很麻烦。有没有办法强制Python将变量名解释为文字python字符串来调用字典或子例程?
发布于 2021-02-09 04:21:15
您需要删除括号,并在字典的元素之间添加逗号。因此,它将是这样的:
veh1 = {
"config_1":1,
"config_2":"a"
}
veh2 = {
"config_1":3,
"config_2":"b"
}
type = veh1
print(type["config_1"])正如jarmod所建议的,您可能需要这样的字典:
dicts= {"veh1": {"config_1":1, "config_2":"a"}, "veh2": {"config_1":3, "config_2":"b"}}
type = "veh1"
print(dicts[type]["config_1"])https://stackoverflow.com/questions/66108750
复制相似问题