ipython 魔术命令中 % 和 %% 的区别

Difference between % and %% in ipython magic commands

在ipython中使用%timeit%%timeit有什么区别?因为当我使用 ?%timeit?%%timeit 阅读文档时,它是相同的文档。那么,添加 % 作为前缀有什么区别呢?

一般来说,一个百分号被称为 line magic 并且仅适用于同一行上它后面的代码。两个百分号被称为 单元格魔法 ,适用于整个单元格中后面的所有内容。

正如 The Data Science Handbook 中所写:

Magic commands come in two flavors: line magics, which are denoted by a single % prefix and operate on a single line of input, and cell magics, which are denoted by a double %% prefix and operate on multiple lines of input.

一些魔术命令,例如timeit,可以用作线魔术或单元魔术:

用作线魔术:

%timeit y = 2 if x < 3 else 4

用作细胞魔法:

%%timeit
if x < 3:
    y=2
else:
    y=4