
我有一個列表列表,並且我使用嵌套\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
當我嘗試使用它時,它超出了範圍。當它仍在範圍內時會使用它。