我想建立一個包含要在 foreach 迴圈中使用的計數器的特定值的陣列。所以我想定義一個命令,將實際計數器值加到列表末尾。我能做的是:
\documentclass{standalone}
\usepackage{pgfmath,pgffor}
\begin{document}
\def\names{{"Katie","Frank","Laura","Joe"}}%
\newcounter{lines}%
\setcounter{lines}{3}%
\def\arr{1,\arabic{lines}}%
\foreach \i in \arr {%
Name \i: \pgfmathparse{\names[\i]}\pgfmathresult, }
\end{document}
但我需要的是一個空列表arr
和函數,我可以用它來填入像eg這樣arr
的值。lines
\addtoarr{\arabic{lines}}
我嘗試使用lstdock
類似的包:
\let\arr\@empty
\def\addtolist#1#2{%
\lst@lAddTo#1{#2}}
\addtolist{\arr}{\arabic{lines}}
但這給了我一個我不明白的錯誤。
答案1
方法有多種,這裡是一種
\documentclass{article}
\usepackage{pgfmath,pgffor}
\begin{document}
\def\names{{"Katie","Frank","Laura","Joe"}}%
\newcounter{lines}%
\setcounter{lines}{1}%
\newcommand*\arr{}%
\newcommand{\mtadd}{%
\ifx\arr\empty
\edef\arr{\arabic{lines}}
\else\edef\arr{\arr,\arabic{lines}}
\fi}
\mtadd
\setcounter{lines}{3}%
\mtadd
\foreach \i in \arr {%
Name \i: \pgfmathparse{\names[\i]}\pgfmathresult, }
\end{document}
答案2
如果您只是想吐出清單中的一些內容,也許以下內容可能會感興趣:
\documentclass{article}
\usepackage{etoolbox}
\newcommand{\listsep}{, }
\makeatletter
\newcommand{\@insertlistsep}{}
\newcounter{@listname}
\newcommand{\addtolist}[1]{%
\stepcounter{@listname}% Add one person to counter
\expandafter\@namedef\expandafter{@listnames:\the@listname}{#1}}% Define counter-based name
\newcommand{\printlist}[1]{%
\renewcommand{\@insertlistsep}{\renewcommand{\@insertlistsep}{\listsep}}% https://tex.stackexchange.com/a/89187/5764
\renewcommand*{\do}[1]{\@insertlistsep Name~##1: \textbf{\@nameuse{@listnames:##1}}}% How each item will be processed
\docsvlist{#1}}% Process list
\makeatother
\begin{document}
\addtolist{Katie}% 1
\addtolist{Frank}% 2
\addtolist{Laura}% 3
\addtolist{Joe}% 4
\printlist{1,2}
\printlist{}
\printlist{1,3,4}
\printlist{3,3,3}
\end{document}
如果需要,額外的工作將是建立一個\clearlist
功能,以及一些錯誤檢查以確保您不會存取清單之外的元素。
清單處理討論於如何迭代逗號分隔的清單?