鉴于 mwe:
\documentclass{article}
\usepackage{etoolbox}
\begin{document}
\listadd\terms{First item of the list}
\listadd\terms{Second item which has punctuation such as, commas, potentially a period and maybe even other things!}
\listadd\terms{And the last one}
\begin{enumerate}%
\forlistloop{\item}{\terms}%
\end{enumerate}%
\end{document}
实现以下目标的最简单方法是什么?
\begin{enumerate}%
\selectiveforlistloop{\item}{\terms}{1,3}%
\end{enumerate}%
目标是仅显示选定的元素,在本例中是元素编号 1 和 3。
答案1
\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\newcommand\selectiveforlistloop[4][]{%
\edef\iaux{0}%
\renewcommand*{\do}[1]{\edef\iaux{\the\numexpr\iaux+1}%
\expanded{\noexpand\in@{,\iaux,}{,#4,}}%
\ifin@
#2 ##1
\fi}%
\dolistloop{#3}%
}
\makeatother
\begin{document}
\listadd\terms{First item of the list}
\listadd\terms{Second item which has punctuation such as, commas, potentially a period and maybe even other things!}
\listadd\terms{And the last one}
\begin{enumerate}%
\selectiveforlistloop{\item}{\terms}{1,3}%
\end{enumerate}%
\end{document}
答案2
我可以建议一种基于的相当通用的方法expl3
。
\documentclass{article}
\usepackage{amsthm} % for `\@addpunct
\ExplSyntaxOn
% borrow \@addpunct
\cs_new_eq:Nc \addpunct { @addpunct }
\NewDocumentCommand{\listadd}{mm}
{
% create the sequence where storing the items if not existent
\seq_if_exist:cF { l_johnchris_list_#1_seq } { \seq_new:c { l_johnchris_list_#1_seq } }
% store the items
\seq_put_right:cn { l_johnchris_list_#1_seq } { #2 }
}
\NewDocumentCommand{\listextract}{mmo}
{
% define the function to use according to the template
\cs_set_protected:Nn \__johnchris_list_extract:n { #2 }
\IfNoValueTF { #3 }
{% no optional argument, use the whole sequence
\seq_map_function:cN { l_johnchris_list_#1_seq } \__johnchris_list_extract:n
}
{% the optional argument is a list of item numbers; extract them in a temporary sequence
\seq_clear:N \l__johnchris_list_temp_seq
\clist_map_inline:nn { #3 }
{
\seq_put_right:Nx \l__johnchris_list_temp_seq { \seq_item:cn { l_johnchris_list_#1_seq } {##1} }
}
% do the mapping on the temporary sequence
\seq_map_function:NN \l__johnchris_list_temp_seq \__johnchris_list_extract:n
}
}
\ExplSyntaxOff
\begin{document}
\listadd{terms}{First item of the list}
\listadd{terms}{Second item which has punctuation such as, commas,
potentially a period and maybe even other things!}
\listadd{terms}{And the last one}
\begin{enumerate}
\listextract{terms}{\item #1\addpunct{.}}
\end{enumerate}
\begin{enumerate}
\listextract{terms}{\item \textit{#1}}[1,3]
\end{enumerate}
\end{document}
第二个参数\listextract
是如何使用存储项目的模板,其中#1
代表循环中的当前项目。
\addpunct
只是为了举例说明如何使用模板。