我试图迭代列表,列表中的变量是字典名称,然后迭代这些字典中的键 我的代码是这样的:
IA = {"V":"CVolt","T":"CTemp"}
CLR = {"V":"CLR_Volt","T":"CLR_Temp"}
GT = {"V":"GT_CVolt","T":"GT_Temp"}
PP = ["IA","GT","CLR"]
AFT = {"IA":0,"GT":0,"CLR":0}
AFV = {"IA":0,"GT":0,"CLR":0}
Voltage=0
Vs ={"IA":0.85,"GT":0.85,"CLR":0.85}
Tempreture = 0
Ts ={"IA":30,"GT":30,"CLR":30}
EAK = 7e3
Stress = {"IA":0,"GT":0,"CLR":0}
C = 1
Seff={"IA":0,"GT":0,"CLR":0}
csv.DictReader
with open(File,"r+") as Fin:
reader = csv.DictReader(Fin, dialect='excel')
for line in reader:
for i in PP:
AFT[i] = math.exp(EAK*((1/Ts[i])-(1/float(line[i["T"]]))))
AFV[i] = math.exp(float(line[i["T"]])-Vs[i])
Stress[i] = AFT[i] * AFV[i]
Seff[i] = Seff[i]+Stress[i]
我的问题是如何获得字典i中Key的值
AFT[i] = math.exp(EAK*((1/Ts[i])-(1/float(line[i["T"]]))))
在这种情况下,在第一个循环中我想获得行[“CTemp”]
欢迎任何建议或不同方法
答案 0 :(得分:1)
你可以使用python内置的locals()函数:
>>> IA = {"V":"CVolt","T":"CTemp"}
>>> locals()['IA']
{'T': 'CTemp', 'V': 'CVolt'}
>>> locals()['IA']['T']
'CTemp'
或更好,将你的变量放在一个大字典中:
>>> vars = {
'IA': {"V":"CVolt","T":"CTemp"},
'CLR': {"V":"CLR_Volt","T":"CLR_Temp"},
...
}
>>> vars['IA']
{'T': 'CTemp', 'V': 'CVolt'}
>>> vars['IA']['T']
'CTemp'
感谢@damienfrancois与当地人完成答案:
math.exp(EAK*((1/Ts[i])-(1/float(line[locals()[i]['T']]))))
与vars dict:
math.exp(EAK*((1/Ts[i])-(1/float(line[vars[i]['T']]))))
答案 1 :(得分:0)
您可以像这样更改代码
AFT[i] = math.exp(EAK*((1/Ts[i])-(1/float(line[eval(i)["T"]]))))
请注意使用eval
将字符串IA
转换为名为IA
的对象。
使用locals()
或容器词典可能更好;看@ Guy的答案。