为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

萧十郎 2021-07-08 14:02:09
我想将 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
查看完整描述

2 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

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]



查看完整回答
反对 回复 2021-07-13
  • 2 回答
  • 0 关注
  • 200 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信