是否可以使用 jupyter notebook 中的代码添加或删除单元格?

is it possible to add cells or delete cells using codes in jupyter notebook?

是否可以使用代码在jupyter notebook中添加或删除单元格?

例如:我们可以使用范围为 10 的 for 循环来创建 10 个单元格并可能在其中执行某些操作吗?

大部分代码在 this GitHub issue 的讨论中提供。

您可以使用以下代码以编程方式在当前单元格下方附加 10 个新代码单元格。

from IPython.display import display, Javascript

# create 10 cells
for i in range(10):
    display(Javascript('''
        let cell = IPython.notebook.insert_cell_{}("{}")
        cell.set_text("{}")
        '''.format('below', 'code', "print('Hello World!')")));
    add_cell('print(\'Hello World\')')

如果你想执行一个,或者可能全部,你可以使用下面的代码。

# execute the 3rd cell of the notebook
display(Javascript('IPython.notebook.execute_cell(3)'))

以上将执行笔记本中的第三个单元格。您可以遍历要执行的索引。