你误解了display_markdown() 的作用。它不是转换表示格式的函数。 IPython 不使用 Markdown 来显示数组,它只是在这种特定情况下输出纯文本。
IPython 显示系统希望对象提供格式化的输出它们自己,markdown 只是支持的不同格式之一。因为对象可以支持多种格式,所以您有时需要明确选择一种特定格式。 display_markdown() 允许您选择降价表示并忽略其他表示。但是如果一个对象没有有一个特定的降价表示,它的标准repr() 字符串会被使用,作为一个后备。请参阅集成文档的Rich Display section。
Numpy 数组没有降价表示,所以 display_markdown() 没有任何可使用的。您看到的打印只是repr(eye(3)) 生成的字符串。所以你可以只使用repr(eye(3)),并在markdown中使用它,用反引号括起来:
A = np.eye(3)
markdown_repr = f"```\n{A!r}\n```"
!r 语法告诉 Python 获取 repr() 的输出。上面产生了字符串:
"```\narray([[1., 0., 0.],\n [0., 1., 0.],\n [0., 0., 1.]])\n```
如果您想在 LaTeX 中表示数组,那么有些项目确实可以生成这样的 numpy 数组表示形式,您可以使用;如果您将它们的结果包装在 $$ 行中,那么您可以将它们视为降价输出,因为 Jupyter 支持嵌入式 Mathjax 表达式(LaTeX 的一个子集)。
例如,使用array-to-latex:
from array_to_latex import to_ltx
to_markdown = lambda m: f"$$\n{to_ltx(m, print_out=False)}\n$$"
print(to_markdown(A))
生产
$$
\begin{bmatrix}
1.00 & 0.00 & 0.00\\
0.00 & 1.00 & 0.00\\
0.00 & 0.00 & 1.00
\end{bmatrix}
$$
您没有有使用库(您可以编写自己的文本操作代码来执行类似的操作),但您不能使用 IPython 来执行此操作。强>
当然,一旦有了这样的函数,你不仅可以直接使用它,还可以教 IPython 将它用于任何 numpy 数组。您可以使用 IPython 将其注册为 text/markdown 的格式化程序,作为 third-party formatter function:
md_formatter = get_ipython().display_formatter.formatters["text/markdown"]
md_formatter.for_type(np.ndarray, to_markdown)
因为我使用的库输出 LaTeX,所以您可以直接使用 to_ltx()(使用 print_out=False)来生成 LaTeX 输出,这也会在您回显数组时产生 Mathjax 输出:
latex_formatter = get_ipython().display_formatter.formatters["text/latex"]
latex_formatter.for_type(np.ndarray, lambda m: to_ltx(m, print_out=False))
无论哪种方式,现在您都会看到数组的 MathJax 渲染:
现在,如果您想访问对象提供的不同格式到 IPython,那么您想使用IPython.core.formatters.format_display_data() function;这为您提供了两个字典,第一个是具有各种表示 mime 类型作为键的字典。如果该对象有可用的降价转换,那么您会在 "text/markdown" 键下找到它:
from IPython.core.formatters import format_display_data
formatted, metadata = format_display_data(A)
formatted["text/markdown"]
因为我已经为 numpy 数组注册了一个 markdown 格式化程序,所以上面为我们生成了 to_markdown() 的输出:
'$$\n\\begin{bmatrix}\n 1.00 & 0.00 & 0.00\\\\\n 0.00 & 1.00 & 0.00\\\\\n 0.00 & 0.00 & 1.00\n\\end{bmatrix}\n$$'
但是如果没有额外的富显示注册,你得到的只是一个"text/plain" 条目。