python 将dictionary转为变量

bigzhu posted @ Jul 26, 2010 11:09:00 AM in python , 2336 阅读

Python有两个内置的函数,locals 和 globals,它们提供了基于字典的访问局部和全局变量的方式。

前面这句话是预知识。
locals是只读的,改也没用,单独拿出来说是为了避免自以为是的拿这个想实现局部转换

有一个dic={x:1,y:2}

想弄成全局变量那就 globals().update(dic)

有什么用呢?
变参函数的时候就方便了。

def test(**arg):
    print args['x']
    print args['y']
    print args['x'] args['y']
    pring args['z']
可以改成

def test(**arg):
    globals().update(arg)
    print x
    print y
    print x y
    print z
不过函数多了全像这样搞,一堆全部变量,互相还有交错,估计你会疯掉.
看下局部怎么弄
局部变量

def test(**arg):
    print args['x']
    print args['y']
    print args['x'] args['y']
    pring args['z']
可以改成

def test(**arg):
    for k, v in arg.items():
        exec “%s=’%s’”%(k,v)
    globals().update(arg)
    print x
    print y
    print x y
    print z

 

———- 已转发邮件 ———-
发件人: 一凡猪 <vermiliondun@gmail.com>
日期: 2010年7月26日 下午1:56
主题: python 将dictionary转为变量
收件人: blog <VermilionDun.worile@blogger.com>

 

Python有两个内置的函数,locals 和globals,它们提供了基于字典的访问局部和全局变量的方式。

前面这句话是预知识。

有一个dic={x:1,y:2}

想弄成局部变量那就locals.update(dic)
全局那就globals.update(dic)

有什么用呢?
变参函数的时候就方便了。

def test(**arg):
    print args['x']
    print args['y']
    print args['x'] args['y']
    pring args['z']
可以改成

def test(**arg):
    locals.update(arg)
    print x
    print y
    print x y
    print z


CBSE 4th Class Solu 说:
Sep 08, 2023 05:42:28 PM

CBSE CBSE 4th Class Solutions 2024 Solutions 2024 Final Exam help Students Prepare for Subject Wise Central Board Exam, our Website Provides Chapter Wise Pdf format Central Board Solution 2024, Both Subject Problems Detailed Solution are Provided, CBSE Solutions 2024 for CBSE Class Solutions 2024 help Students Better Performance in Final Examination 2024, CBSE Solution is the Good Guidance to CBSE 4th Class Solutions 2024 help you Prepare for CBSE Exam, CBSE Solution are used not only by CBSE but also by all India State Education Boards.CBSE Solutions 2024 for Class has been Solved by the Experience Teachers of CBSE Guide. CBSE Class Books Solutions 2024 are available in PDF format our Website.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter