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


157

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


11
即使使用Python,最后的答案也将是
42。– Tomalak

3
42?每个人都错过了机会来获得Incantato优先参考!
amindfv 2011年

[输入] >>> _1 [输出] >>> 42?每个人都错过了机会来获得Incantato优先参考!
gregory

Answers:


236

下划线。

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

19
但是,它仅在交互式外壳中有效。不要依靠它来编写脚本。
John Fouhy

5
此外,如果该变量_已预先分配,则无法使用。这并不罕见,因为这符号也用于一次性变量(见stackoverflow.com/questions/5893163/...

3
是的,最后一块。这样,我就可以将交互式python用作计算器。
Jaakko,

81

仅作记录,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

4
在1.2.1中也发现_____偶然出现了。
西罗Santilli郝海东冠状病六四事件法轮功2015年

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.