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

发布于 2025-01-09 19:28:13 字数 93 浏览 5 评论 0原文

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

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

is it possible to use code to add or delete cells in jupyter notebook?

For example: can we use a for loop in range of 10 that creates 10 cells and perhaps executes something in it ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

櫻之舞 2025-01-16 19:28:13

大部分代码在此 GitHub 问题的讨论中提供。

您可以使用以下代码以编程方式在当前单元格下方附加 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)'))

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

Most of the code is provided in a discussion in this GitHub issue.

You could use the following code to programmatically append 10 new code cells below the current cell.

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\')')

If you want to execute one, or possibly all of them, you could use the following code.

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

The above will execute the third cell in the notebook. You could loop over the indices that you want to execute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文