我想将 list 分配给变量,而list和variable都存储在字典中measurements。这是measurements具有较少变量的 Python 2 版本:
measurements = {'tg': [8.184e+16, 8.345e+16, 8.045e+16, 8.520e+16, 8.322e+16, 7.622e+16, 4.305e+16, 2.203e+16]}
def f():
for key,val in measurements.items():
exec(key + ' = val') in globals(),locals()
print (tg)
f()
但是,正如在另一个问题中提到的,它不适合 Python 3。如果我这样编写代码:
measurements = {'tg': [8.184e+16, 8.345e+16, 8.045e+16, 8.520e+16, 8.322e+16, 7.622e+16, 4.305e+16,
2.203e+16]}
def f():
for key,val in measurements.items():
ldict = {}
exec(key + ' = val', globals(),ldict)
key = ldict[key]
# exec(key + ' = val') in globals(),locals()
print (tg)
f()
我收到此错误: NameError: name 'val' is not defined
繁星coding
相关分类