迭代列表列表?

迭代列表列表?

跟进使用 etoolbox 自定义元素列表 特别是第二种解决方案:有没有一种方便的方法来迭代这些列表?

例子:

\documentclass{article}

\usepackage{tikz}

\ExplSyntaxOn
\NewDocumentCommand{\newList}{m}
 {
  \seq_new:c { l_kees_list_#1_seq }
 }
\NewDocumentCommand{\addToList}{mm}
 {
  \seq_put_right:cn { l_kees_list_#1_seq } { #2 }
 }
\NewDocumentCommand{\getFromList}{mm}
 {
  \seq_item:cn { l_kees_list_#1_seq } { #2 }
 }
\NewDocumentCommand{\getListLength}{m}
 {
   \seq_count:c { l_kees_list_#1_seq } 
 }
\NewDocumentCommand{\getList}{m}
 {
   \seq_use:cn { l_kees_list_#1_seq }  { , }
 } 
\ExplSyntaxOff



\begin{document}


\newList{listA}
\newList{listB}
\addToList{listA}{one}
\addToList{listA}{two}
\addToList{listA}{three}
\addToList{listB}{oneinB}
\addToList{listB}{anoterinB}

% this works, but is cumbersome: 
\foreach \n in {1,...,\getListLength{listA}} {n: \n, \getFromList{listA}{\n} }
\foreach \n in {1,...,\getListLength{listB}} {n: \n, \getFromList{listB}{\n} }

% not sure why this does not expand properly? 
\foreach \i in {\getList{ListA}} {i: \i }

\end{document}

它给出错误消息:

! Use of \??? doesn't match its definition.
<argument> \???
                 ! LaTeX Error: Erroneous variable \l_kees_list_ListA_seq used!
l.46 \foreach \i in {\getList{ListA}} {i: \i }

(为什么是 foreach?因为这些循环最终需要进入 tikzpicture)

谢谢!

答案1

只是不要使用\foreach

这里\listLoop有两个参数:第一个是列表名称,第二个是#1代表当前周期和#2项目的模板。

\documentclass{article}

\usepackage{tikz}

\ExplSyntaxOn

%%% Lists
\NewDocumentCommand{\newList}{m}
 {
  \seq_new:c { l_kees_list_#1_seq }
 }
\NewDocumentCommand{\addToList}{mm}
 {
  \seq_put_right:cn { l_kees_list_#1_seq } { #2 }
 }
\NewDocumentCommand{\getFromList}{mm}
 {
  \seq_item:cn { l_kees_list_#1_seq } { #2 }
 }
\NewDocumentCommand{\getListLength}{m}
 {
   \seq_count:c { l_kees_list_#1_seq }
 }
\NewDocumentCommand{\getList}{m}
 {
   \seq_use:cn { l_kees_list_#1_seq }  { , }
 }

%%% Loops
\NewDocumentCommand{\loopList}{m +m}
 {
  \seq_map_indexed_inline:cn { l_kees_list_#1_seq } { #2 }
 }
\cs_generate_variant:Nn \seq_map_indexed_inline:Nn { c }
\ExplSyntaxOff



\begin{document}


\newList{listA}
\newList{listB}
\addToList{listA}{one}
\addToList{listA}{two}
\addToList{listA}{three}
\addToList{listB}{oneinB}
\addToList{listB}{anoterinB}

% this works, but is cumbersome:
\foreach \n in {1,...,\getListLength{listA}} {n: \n, \getFromList{listA}{\n} }

%\foreach \n in {1,...,\getListLength{listB}} {n: \n, \getFromList{listB}{\n} }

% this is better
\loopList{listA}{n: #1, #2 }

\end{document}

在此处输入图片描述

相关内容