带有列表的 IPython Notebook 单元格

带有列表的 IPython Notebook 单元格

我想在我的文档中包含一些类似于此图中的 IPython Notebook 单元的代码示例:

在此处输入图片描述

我使用下面的代码生成了一些看起来有点像的东西:

\documentclass{article}

\usepackage{color}
\definecolor{light-gray}{gray}{0.95}

\usepackage{listings}
\lstset{
    basicstyle=\footnotesize\ttfamily,
    escapechar=¢,
    language=python,
    frame=single,
    frameround=tttt,
    showstringspaces=false,
    backgroundcolor=\color{light-gray}
}
\newcommand*{\ipythonprompt}[1]{\makebox[0pt][r]{\textbf{In [#1]:}\hspace{1em}}}

\begin{document}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Here are two IPython cells:
\begin{lstlisting}
¢\ipythonprompt{1}¢ n = 10
\end{lstlisting}

\begin{lstlisting}
¢\ipythonprompt{2}¢ for i in range(n):
    print('i = ', i)
\end{lstlisting}

\end{document}

它看起来是这样的:

在此处输入图片描述

但我有几个问题:

  • 角不太正确:有点歪而且太圆了;

  • 提示In [1]:等位于边缘,但我希望它们位于正文中,并且灰色单元格区域位于它们的右侧。

有人能建议我如何实现这个目标吗?

答案1

我建议你使用tcolorbox包及其与的交互listings

在此处输入图片描述

代码(根据需要调整设置):

\documentclass{article}
\usepackage{xcolor}
\usepackage[many]{tcolorbox}
\tcbuselibrary{listings}

\definecolor{light-gray}{gray}{0.95}

% the space reserved between for the ``In'' numbers and the code
\newlength\inwd
\setlength\inwd{1.3cm}

\newcounter{ipythcntr}

\newtcblisting{ipythonnb}[1][\theipythcntr]{
  enlarge left by=\inwd,
  width=\linewidth-\inwd,
  enhanced,
  boxrule=0.4pt,
  colback=light-gray,
  listing only,
  top=0pt,
  bottom=0pt,
  overlay={
    \node[
      anchor=north east,
      text width=\inwd,
      font=\footnotesize\ttfamily\color{blue!50!black},
      inner ysep=2mm,
      inner xsep=0pt,
      outer sep=0pt
      ] 
      at (frame.north west)
      {\stepcounter{ipythcntr}In [#1]:};
  }
  listing options={
    basicstyle=\footnotesize\ttfamily,
    language=python,
    escapechar=¢,
    showstringspaces=false,
  },
}

\begin{document}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Here are two IPython cells:
\begin{ipythonnb}
n = 10
\end{ipythonnb}

\begin{ipythonnb}
for i in range(n):
    print('i = ', i)
\end{ipythonnb}

\begin{ipythonnb}[13]
n = 10
\end{ipythonnb}

\end{document}

环境的可选参数ipythonnb允许手动控制部分的编号In

相关内容