atp*_*atp 61 python dictionary
有没有更简单的方法在Python(2.7)中执行此操作?:注意:这不是任何花哨的东西,比如将所有局部变量放入字典中.只是我在列表中指定的那些.
apple = 1
banana = 'f'
carrot = 3
fruitdict = {}
# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?
for x in [apple, banana, carrot]:
fruitdict[x] = x # (Won't work)
Run Code Online (Sandbox Code Playgroud)
dr *_*bob 67
for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 14
该globals()函数返回包含所有全局变量的字典.
>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}
Run Code Online (Sandbox Code Playgroud)
还有一个类似的函数叫做locals().
我意识到这可能不是你想要的,但它可以提供一些深入了解Python如何提供对变量的访问.
编辑:听起来你的问题可以通过首先简单地使用字典来解决:
fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
Run Code Online (Sandbox Code Playgroud)
小智 6
单线是: -
fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141978 次 |
| 最近记录: |