5

Say I ran an expensive operation foo() which returns me a large list, but I forgot to save the output of foo() inside a variable.

Let's assume if I run foo() again, I will get a different output.

But I really need the output from the first time I ran foo().

In effect, I am asking if there is some buffer that stores the output of the last command, which I could read?

4

2 回答 2

5

_(单下划线)适用于 Windows 的 python 3,也适用于其他版本:

>>> 1 + 1
2
>>> x = _
>>> x
2
于 2014-03-10T20:42:13.213 回答
2

_字符(单下划线)在所有 Python 版本中被定义为最后一次评估的输出,但仅限于交互式 shell 中。请参阅:文档

例子:

>>> def foo():
>>>     return 3
>>> foo()
3
>>> _ + 1
4

根据您的问题,听起来您只关心如何在交互式外壳中执行此操作;为了完整起见,上述功能没有为非交互式外壳定义。

于 2014-03-11T03:44:43.953 回答