创建单独变量字典的更简单方法? [英] Simpler way to create dictionary of separate variables?

查看:48
本文介绍了创建单独变量字典的更简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够以字符串的形式获取变量的名称,但我不知道 Python 是否具有那么多的内省功能.类似的东西:

<预><代码>>>>打印(my_var.__name__)'my_var'

我想这样做是因为我有一堆变量我想变成像这样的字典:

bar = Truefoo = 错误>>>my_dict = dict(bar=bar, foo=foo)>>>打印 my_dict{'foo': False, 'bar': True}

但我想要比这更自动化的东西.

Python 有 locals()vars(),所以我想有办法.

解决方案

你想这样做吗?

dict( (name,eval(name)) for name in ['some','list','of','vars'] )

例子

<预><代码>>>>一些= 1>>>列表= 2>>>的= 3>>>变量= 4>>>dict( (name,eval(name)) for name in ['some','list','of','vars'] ){'list': 2, 'some': 1, 'vars': 4, 'of': 3}

I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:

>>> print(my_var.__name__)
'my_var'

I want to do that because I have a bunch of variables I'd like to turn into a dictionary like :

bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict 
{'foo': False, 'bar': True}

But I'd like something more automatic than that.

Python have locals() and vars(), so I guess there is a way.

解决方案

Are you trying to do this?

dict( (name,eval(name)) for name in ['some','list','of','vars'] )

Example

>>> some= 1
>>> list= 2
>>> of= 3
>>> vars= 4
>>> dict( (name,eval(name)) for name in ['some','list','of','vars'] )
{'list': 2, 'some': 1, 'vars': 4, 'of': 3}

这篇关于创建单独变量字典的更简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆