简洁地在ipython笔记本中打印变量名称和值

时间:2017-10-02 02:06:35

标签: ipython-notebook

我想打印单元格中定义的所有变量及其值,而不必执行

print('x:', x)
print('y:', y)
print('z:', z)

... 是这样的:      %p x y z 它会完成上述相同的工作吗?

3 个答案:

答案 0 :(得分:1)

使用ipython笔记本,您可以使用:

#without turning on %automagic
%who
#with turning on %automagic
who

这将显示内存中保存的所有变量名称

#without turning on %automagic
%whos
#with turning on %automagic
whos

这将显示变量名称及其值

参考文献:

iPython Magic

Relevant StackOverflow Question

答案 1 :(得分:0)

x = 'test1'
y = 'test2'
z = 'test3'

print('x: %s, y: %s, z: %s'%(x, y,z))

如果x,y,z变量是整数,则应使用%d而不是%s。

答案 2 :(得分:0)

你可以创建一个行魔术来做那件事。如下所示

from IPython.core.magic import register_line_magic
@register_line_magic
def p(args):
    for key in args.split(" "):
        print globals()[key]