本文介绍了覆盖 jupyter notebook 中的先前输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一部分代码运行了特定的时间,每 1 秒输出如下内容:迭代 X,得分 Y.我将用我的黑盒函数替换这个函数:

Let's assume I have a part of code that runs for some specific amount of time and each 1 second outputs something like this: iteration X, score Y. I will substitute this function with my black box function:

from random import uniform
import time

def black_box():
    i = 1
    while True:
        print 'Iteration', i, 'Score:', uniform(0, 1)
        time.sleep(1)
        i += 1

现在,当我在 Jupyter notebook 中运行它时,它在每个第二个:

Now when I run it in Jupyter notebook, it output a new line after each second:

Iteration 1 Score: 0.664167449844
Iteration 2 Score: 0.514757592404
...

是的,当输出变得太大后,html 变得可滚动,但问题是除了当前最后一行之外,我不需要任何这些行.因此,我不想在 n 秒后显示 n 行,而是只显示 1 行(最后一行).

Yes, after when the output becomes too big, the html becomes scrollable, but the thing is that I do not need any of these lines except of currently the last one. So instead of having n lines after n seconds, I want to have only 1 line (the last one) shown.

我没有在文档中或通过魔法寻找任何类似的东西.一个问题,标题几乎相同,但无关紧要.

I have not found anything like this in documentation or looking through magic. A question with almost the same title but irrelevant.

推荐答案

@cel 是对的:ipython notebook 清除代码中的单元格输出

不过,使用 clear_output() 会使您的笔记本产生抖动.我建议也使用 display() 函数,就像这样(Python 2.7):

Using the clear_output() gives makes your Notebook have the jitters, though. I recommend using the display() function as well, like this (Python 2.7):

from random import uniform
import time
from IPython.display import display, clear_output

def black_box():
i = 1
while True:
    clear_output(wait=True)
    display('Iteration '+str(i)+' Score: '+str(uniform(0, 1)))
    time.sleep(1)
    i += 1

这篇关于覆盖 jupyter notebook 中的先前输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:08
查看更多