[Tex/LaTex] Foreach loop between two lists

loopstikz-pgf

\documentclass{article}
\usepackage{tikz}

\def\firstlist{0,1,2}
\def\secondlist{0,1,2}

\newcommand{\testa}{
 \foreach \x/\y in {\firstlist/\secondlist} {
    \draw(0,\x)--(1,\y);
    }
}

\newcommand{\testb}{
 \foreach \x/\y in {0/0,1/1,2/2} {
    \draw(0,\x)--(1,\y);
    }
}
\begin{document}
\begin{tikzpicture}
\testa
\end{tikzpicture}
\end{document}

How can I make the output of the \testa command equal to the output of the \testb command?

Best Answer

Here is a very simple solution:

\documentclass{article}
\usepackage{tikz}

\def\firstlist{0,1,2}
\def\secondlist{0,1,2}

\newcommand{\testa}{
  \foreach \x [count=\c,evaluate=\c as \y using {{\secondlist}[\c-1]}]  in \firstlist {
    \draw(0,\x)--(1,\y);
  }
}

\begin{document}
\begin{tikzpicture}
\testa
\end{tikzpicture}
\end{document}

An extended solution defining the new style parallel foreach. You can use multiple parallel lists:

\documentclass{standalone}
\usepackage{tikz}

\pgfset{
  foreach/parallel foreach/.style args={#1in#2via#3}{evaluate=#3 as #1 using {{#2}[#3-1]}},
}

\def\firstlist{0,1,2,10,11}
\def\secondlist{0,1,2,10,11}
\def\thirdlist{1,2,10,11,0}

\newcommand{\testa}{
  \foreach \x [count=\c,
  parallel foreach=\y in \secondlist via \c,
  parallel foreach=\z in \thirdlist via \c]
  in \firstlist
  {
    \node[left] at (0,\x) {\x};
    \draw(0,\x)--(1,\y);
    \draw[red](0,\x)--(1,\z);
  }
}

\begin{document}
\begin{tikzpicture}
\testa
\end{tikzpicture}
\end{document}

Both methods use the array features of pgfmath: they evaluate each element as a math formula. If you want string elements, use quotes ("...").

\documentclass[margin=1mm]{standalone}
\usepackage{tikz}

\pgfset{
  foreach/parallel foreach/.style args={#1in#2via#3}{
    evaluate=#3 as #1 using {{#2}[#3-1]}
  },
}

\def\firstlist{0,1,2,10,11}
\def\secondlist{0,1,2,10,11}
\def\thirdlist{1,2,10,11,0}
\def\fourthlist{"label a","label b","label c","label $\delta$","label e"}
\newcommand{\testa}{
  \foreach \x [count=\c,
  parallel foreach=\y in \secondlist via \c,
  parallel foreach=\z in \thirdlist via \c,
  parallel foreach=\lab in \fourthlist via \c]
  in \firstlist
  {
    \node[left] at (0,\x) {\lab};
    \draw(0,\x)--(1,\y);
    \draw[red](0,\x)--(1,\z);
  }
}

\begin{document}
\begin{tikzpicture}
\testa
\end{tikzpicture}
\end{document}

enter image description here