Python 给定字符串的变量
Python target a variable given the string
编辑:一般的想法是使用 %store magic 将所有变量存储在我的 Jupyter Notebook 中,以便使用 %store -r 将它们全部返回到下一个会话。
我正在尝试使用:
% store
我需要存储变量。有:
dir()
我获得了一个字符串列表,其中包含我在该行之前创建的所有变量名称,例如:
['a','b','c']
有没有办法执行:
%store a
%store b
%store c
知道变量的字符串?
我试过这个:
for i in dir():
%store eval(i)
但它给出:UsageError: Unknown variable 'eval(i)'
我该如何处理?有没有办法将所有本地环境保存在 Jupyter Notebook 中以备下次使用?
编辑:
for i in dir():
%store locals()[i]
给出:使用错误:未知变量'locals()[i]'
正如@abarnert 所建议的那样,您可以 运行 以编程方式使用魔术线,例如:
In []:
import IPython
store = IPython.get_ipython().find_line_magic('store')
a = b = c = 10
for i in ['a', 'b', 'c']:
store(i)
Out []:
Stored 'a' (int)
Stored 'b' (int)
Stored 'c' (int)
尝试使用 %store
执行此操作的问题是传递给它的字符串未被评估,而是直接在范围内查找,因此出现错误 Unknown variable 'eval(i)'
编辑:一般的想法是使用 %store magic 将所有变量存储在我的 Jupyter Notebook 中,以便使用 %store -r 将它们全部返回到下一个会话。
我正在尝试使用:
% store
我需要存储变量。有:
dir()
我获得了一个字符串列表,其中包含我在该行之前创建的所有变量名称,例如:
['a','b','c']
有没有办法执行:
%store a
%store b
%store c
知道变量的字符串? 我试过这个:
for i in dir():
%store eval(i)
但它给出:UsageError: Unknown variable 'eval(i)' 我该如何处理?有没有办法将所有本地环境保存在 Jupyter Notebook 中以备下次使用?
编辑:
for i in dir():
%store locals()[i]
给出:使用错误:未知变量'locals()[i]'
正如@abarnert 所建议的那样,您可以 运行 以编程方式使用魔术线,例如:
In []:
import IPython
store = IPython.get_ipython().find_line_magic('store')
a = b = c = 10
for i in ['a', 'b', 'c']:
store(i)
Out []:
Stored 'a' (int)
Stored 'b' (int)
Stored 'c' (int)
尝试使用 %store
执行此操作的问题是传递给它的字符串未被评估,而是直接在范围内查找,因此出现错误 Unknown variable 'eval(i)'