如何在每个for循环后清除jupyter笔记本单元中的输出?

Sof*_*dez 4 python image python-3.x jupyter-notebook

因此,对于每个 for 循环,我生成一个图像并要求用户输入“是”或“否”。我希望在生成新图像和新用户输入行之前从单元格中清除图像和用户输入行。相反,只有图像被清除/替换(用户输入行根本不显示)。
这就是现在的样子(for 循环下的所有内容都应该向右缩进): 在此输入图像描述

for filename in os.listdir(folder):
clear_output(wait=True)
split_filename=os.path.splitext(filename)[0] #splitting filename from .jpg
image_id, age=split_filename.split('_', 2) #saving image_id and age
#print([image_id, age])

if int(image_id)>= starting_image_id: #start at a certain image #, specified above    
    image_ids.append(image_id) 
    ages.append(age)
 
    #This line below displays image in original color:
    #display.display(Image.open(os.path.join(folder,filename)))
    
    #These 5 lines below display image in grayscale:
    image = cv2.imread(os.path.join(folder,filename))
    image1 = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    plt.figure()   # create a new figure
    plt.imshow(image1, cmap='gray')
    plt.show()
                     
    attractive_rating=0 #so that while loop will run until user input = y or n 
    while attractive_rating != 'y' and attractive_rating !='n':
        attractive_rating=input('Do you find this face attractive? Enter y/n:')
    attractive_labels.append(attractive_rating) 
    
    if attractive_labels.count('y') > 2 and attractive_labels.count('n')>2:
        break 
Run Code Online (Sandbox Code Playgroud)

小智 7

clear_output您可以在循环末尾使用。

此代码将打印出一些具有指定值的输出。每次迭代前一个输出都会被清除,并显示一个新的输出。

from IPython.display import clear_output

value = 1

while value != 'x':
    value = input('Input a value. Type x to quit.')
    print(f'The value was {value}')
    clear_output(wait=True)
print('Script completed')
Run Code Online (Sandbox Code Playgroud)