我想检索传递给 TikZ 图片作为参数的非数字数组的成员,以将其用作节点标签。 \foreach
在迭代数组时很容易做到这一点,但我无法对单个元素做到这一点。以下是我两次失败的尝试:
\documentclass[tikz]{standalone}
\begin{document}
\tikzset{
pics/mypic/.style n args={1}{
code={
\foreach \a [count=\i] in {#1}{
\node at (\i, 1) {$\a$};
}
% Attempt 1: Doesn't work
% \node at (1, 2) {$#1[0]$};
% Attempt 2: Doesn't compile
% Error: Undefined control sequence. ... Missing $ inserted. ...
\node at (2, 2) {$\pgfmathparse{{#1}[0]}\pgfmathresult$};
}
}
}
\tikz{\pic {mypic={\mathtt{a},\mathtt{b},\mathtt{c}};}}
% \tikz{\pic {mypic={a,b,c};}} % It's the same for this one.
% \tikz{\pic {mypic={0,1,2};}} % Attempt 2 works with this one,
% \tikz{\pic {mypic={0,a,2};}} % but not with this one ("Unknown function `a').
\end{document}
输出:
我希望能够以某种方式绘制一个带有标签的节点#1[0]
。关于第二次尝试,我注意到它对文本数组也会产生同样的错误。它对全数字数组工作正常,但混合数组也会出现问题,即使访问的元素是数字。
答案1
在这里,我使用listofitems
将所需数据读入数组\mydata
。OP建议对我的原始方法进行有用的编辑,方法是将所有listofitems
处理都包含在代码中\tikzset
。
请注意,2
in \mydata[2]
(调用单个数组元素)可以是任何可扩展的计算,其结果为整数。此外,负值表示“反向索引”,即相对于数组的末尾,而不是开头。
\documentclass[tikz]{standalone}
\usepackage{listofitems}
\begin{document}
\tikzset{
pics/mypic/.style n args={1}{
code={
\foreach \a [count=\i] in {#1}{
\node at (\i, 1) {$\a$};
}
\readlist\mydata{#1}
\node at (2, 2) {$\mydata[2]$};
}
}
}
\tikz{\pic {mypic={\mathtt{a},\mathtt{b},\mathtt{c}};}}
\end{document}
答案2
以下命令用于\foreach
检索给定索引处的元素,并将其全局分配给给定的宏。
% Does #1 = #2[#3] with 0-based indexing
\newcommand\arrayget[3]{
\foreach \a [count=\i from 0] in {#2}{
\ifnum #3=\i
\xdef#1{\unexpanded\expandafter{\a}}
\fi
}
}
供好奇者参考:
它应该能够处理任何\foreach
可以处理的事情。演示:
\documentclass[tikz]{standalone}
\newcommand\arrayget[3]{ % Does #1 = #2[#3] with 0-based indexing
\foreach \a [count=\i from 0] in {#2}{
\ifnum #3=\i
\xdef#1{\unexpanded\expandafter{\a}}
\fi
}
}
\begin{document}
\tikzset{
pics/mypic/.style n args={1}{
code={
\foreach \a [count=\i] in {#1}{ \node at (\i, 1) {$\a$}; }
\arrayget{\asd}{#1}{0} \node at (1.5, 2) {$\asd$};
\arrayget{\asd}{#1}{1} \node at (2.0, 2) {$\asd$};
\arrayget{\qwe}{#1}{2} \node at (2.5, 2) {$\qwe$};
}
}
}
\tikz{\pic {mypic={\mathtt{a},\mathtt{b},\mathtt{c}};}}
\tikz{\pic {mypic={a,b,c};}}
\tikz{\pic {mypic={0,1,2};}}
\tikz{\pic {mypic={0,a,2};}}
\end{document}
输出: