如何使用exec根据Python3中的字典将列表分配给变量?

我想将 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


萧十郎
浏览 201回答 2
2回答

繁星coding

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('{} = {}'.format(key, val))    print (tg)    local = locals()    for key in measurements.keys():        print 'Key: ', key, ', Value: ', local[key]f()蟒蛇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():        exec('global {};{} = {}'.format(key, key, val))    print ('tg: ', tg)    vars = globals()    for key in measurements.keys():        print ('Key: ', key, ', Value: ', vars[key])f()输出:[8.184e+16, 8.345e+16, 8.045e+16, 8.52e+16, 8.322e+16, 7.622e+16, 4.305e+16, 2.203e+16]Key:  tg , Value:  [8.184e+16, 8.345e+16, 8.045e+16, 8.52e+16, 8.322e+16, 7.622e+16, 4.305e+16, 2.203e+16]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python