![如何按章节编号对列表进行编号?](https://linux22.com/image/309516/%E5%A6%82%E4%BD%95%E6%8C%89%E7%AB%A0%E8%8A%82%E7%BC%96%E5%8F%B7%E5%AF%B9%E5%88%97%E8%A1%A8%E8%BF%9B%E8%A1%8C%E7%BC%96%E5%8F%B7%EF%BC%9F.png)
我想在我的文档中包含多个带有章节的列表。我还希望每个列表都有标签,例如清单 2.1其中 2 是部分编号,1 是该部分中给定列表的编号。到目前为止,我能够生成以下代码:
\documentclass[a4paper]{article}
\usepackage{listings}
\lstset{frame=Trbl,numbers=left}
\begin{document}
\renewcommand{\thelstlisting}{\thesection.\arabic{lstlisting}}
\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}
但这会产生以下结果:
如何在每个部分开始后重置计数器?
答案1
解决方案是包含包chngcntr
并放置\counterwithin{lstlisting}{section}
在后面\begin{document}
。完整的代码如下
\documentclass[a4paper]{article}
\usepackage{listings,chngcntr}
\lstset{frame=Trbl,numbers=left}
\usepackage{amsmath}
\begin{document}
\counterwithin{lstlisting}{section}
\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}
产生所需的输出: