我有一个列表列表,我正在使用嵌套\foreach
循环来迭代它们。通过使用[count=\var]
,我能够用来\var
访问外循环的长度(在我迭代之后)。但是,我无法使用此方法来访问内循环的长度。在我的例子中,所有内循环应该具有相同的长度,但从技术上讲,我想访问最后一个内循环的长度。这是我目前所拥有的:
\documentclass{article}
\usepackage{tikz}
\begin{document}
% The first two work:
\begin{tikzpicture}
\foreach \from [count=\to] in {2,3,1} {
\draw (\from,1) -- (\to,2);
}
\draw[gray] (0.5,0.5) rectangle (\to+0.5,2.5);
\end{tikzpicture}
\begin{tikzpicture}
\foreach \from [count=\to] in {1,3,2} {
\draw (\from,1) -- (\to,2);
}
\draw[gray] (0.5,0.5) rectangle (\to+0.5,2.5);
\end{tikzpicture}
% This one does not work:
\begin{tikzpicture}
\foreach \list [count=\row] in {{2,3,1},{1,3,2}} {
\foreach \from [count=\to] in \list {
\draw (\from,\row) -- (\to,\row+1);
}
}
\draw[gray] (0.5,0.5) rectangle (\to+0.5,\row+1.5);
\end{tikzpicture}
\end{document}
这就是我想要的结果:
答案1
这将 LaTeX 计数器与 TikZ 宏结合使用。所有计数器操作都是全局的。
\documentclass{article}
\usepackage{tikz}
\newcounter{to}
\newcounter{row}
\begin{document}
\begin{tikzpicture}
\setcounter{to}{0}
\foreach \from in {2,3,1} {
\stepcounter{to}
\draw (\from,1) -- ({\theto},2);
}
\draw[gray] (0.5,0.5) rectangle (\theto+0.5,2.5);
\end{tikzpicture}
\begin{tikzpicture}
\setcounter{to}{0}
\foreach \from in {1,3,2} {
\stepcounter{to}
\draw (\from,1) -- (\theto,2);
}
\draw[gray] (0.5,0.5) rectangle (\theto+0.5,2.5);
\end{tikzpicture}
\begin{tikzpicture}
\setcounter{row}{0}
\foreach \list in {{2,3,1},{1,3,2}} {
\stepcounter{row}
\setcounter{to}{0}
\foreach \from in \list {
\stepcounter{to}
\draw (\from,\therow) -- (\theto,\therow+1);
}
}
\draw[gray] (0.5,0.5) rectangle (\theto+0.5,\therow+1.5);
\end{tikzpicture}
\end{document}
答案2
该解决方案的缺点是需要多次迭代列表,但它避免设置全局变量。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \list [count=\row] in {{2,3,1},{1,3,2}} {
\foreach \from [count=\to] in \list {
\draw (\from,\row) -- (\to,\row+1);
}
}
\foreach \list [count=\count] in {{2,3,1},{1,3,2}} {
\ifx \count \row
\foreach \from [count=\to] in \list {
}
\draw[gray] (0.5,0.5) rectangle (\to+0.5,\row+1.5);
\fi
}
\end{tikzpicture}
\end{document}
我的第一个版本的问题在于,\to
当我尝试使用它时,它超出了范围。当它仍在范围内时,它会使用它。