在交互式Python Shell中获得最后结果

问题:在交互式Python Shell中获得最后结果

在许多符号数学系统(例如Matlab或Mathematica)中,可以使用变量,例如Ans或,%以检索最后计算的值。Python Shell中是否有类似的功能?

In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like Ans or % to retrieve the last computed value. Is there a similar facility in the Python shell?


回答 0

下划线。

>>> 5+5
10
>>> _
10
>>> _ + 5
15
>>> _
15

Underscore.

>>> 5+5
10
>>> _
10
>>> _ + 5
15
>>> _
15

回答 1

仅作记录,ipython会更进一步,您可以使用_及其数值访问每个结果

In [1]: 10
Out[1]: 10

In [2]: 32
Out[2]: 32

In [3]: _
Out[3]: 32

In [4]: _1
Out[4]: 10

In [5]: _2
Out[5]: 32

In [6]: _1 + _2
Out[6]: 42

In [7]: _6
Out[7]: 42

也可以使用%ed宏编辑行范围:

In [1]: def foo():
   ...:     print "bar"
   ...:     
   ...:     

In [2]: foo()
bar

In [3]: %ed 1-2

Just for the record, ipython takes this one step further and you can access every result with _ and its numeric value

In [1]: 10
Out[1]: 10

In [2]: 32
Out[2]: 32

In [3]: _
Out[3]: 32

In [4]: _1
Out[4]: 10

In [5]: _2
Out[5]: 32

In [6]: _1 + _2
Out[6]: 42

In [7]: _6
Out[7]: 42

And it is possible to edit ranges of lines with the %ed macro too:

In [1]: def foo():
   ...:     print "bar"
   ...:     
   ...:     

In [2]: foo()
bar

In [3]: %ed 1-2

回答 2

IPython允许您_通过双(__)和三下划线(___)超越单个下划线,返回倒数第二个和倒数第三个命令的结果。

或者,您也可以使用Out[n],其中n是生成输出的输入的编号:

In [64]: 1+1
Out[64]: 2

...

In [155]: Out[64] + 3
Out[155]: 5

有关更多信息,请参见https://jakevdp.github.io/PythonDataScienceHandbook/01.04-input-output-history.html

IPython allows you to go beyond the single underscore _ with double (__) and triple underscore (___), returning results of the second- and third-to-last commands.

Alternatively, you can also use Out[n], where n is the number of the input that generated the output:

In [64]: 1+1
Out[64]: 2

...

In [155]: Out[64] + 3
Out[155]: 5

For more info, see https://jakevdp.github.io/PythonDataScienceHandbook/01.04-input-output-history.html .