按照条件计算列表中元素的数量

按照条件计算列表中元素的数量

请考虑以下示例:

\documentclass{article}

\begin{document}

\noindent
How do I use \LaTeX 3 to construct a command that prints the number of elements
from a given list that are less than or equal to a given value?\\[\baselineskip]
Example: I want to count the number of commands (\verb|\Aa|--\verb|\Dj|) in the code
\begin{verbatim}
\def\Aa{53} \def\Ab{53} \def\Ac{42} \def\Ad{40} \def\Ae{57}
\def\Af{62} \def\Ag{45} \def\Ah{46} \def\Ai{72} \def\Aj{81}
\def\Ba{59} \def\Bb{65} \def\Bc{50} \def\Bd{64} \def\Be{67}
\def\Bf{50} \def\Bg{53} \def\Bh{55} \def\Bi{46} \def\Bj{51}
\def\Ca{61} \def\Cb{65} \def\Cc{70} \def\Cd{75} \def\Ce{63}
\def\Cf{66} \def\Cg{63} \def\Ch{52} \def\Ci{54} \def\Cj{50}
\def\Da{52} \def\Db{55} \def\Dc{52} \def\Dd{57} \def\De{53}
\def\Df{51} \def\Dg{57} \def\Dh{56} \def\Di{54} \def\Dj{63}
\end{verbatim}
that are less than or equal to $50$. I know that the answer is $32$ but how do I
create a command, say \verb|CountElements|, that gives the output $32$?

\end{document}

输出

问题已包含在示例中。

答案1

数一数。;-)

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\countelements}{mm}
 {% #1 = list of elements, #2 = condition
  \int_zero:N \l__svend_count_elements_int
  \cs_set:Nn \__svend_count_elements:n { #2 }
  \clist_map_inline:xn { #1 }
   {
    \int_compare:nT
     { \__svend_count_elements:n { ##1 } }
     { \int_incr:N \l__svend_count_elements_int }
   }
  \int_to_arabic:n { \l__svend_count_elements_int }
 }
\int_new:N \l__svend_count_elements_int
\cs_generate_variant:Nn \clist_map_inline:nn { x }
\ExplSyntaxOff

\def\Aa{53}
\def\Ab{53}
\def\Ac{42}
\def\Ad{40}
\def\Ae{57}
\def\Af{62}
\def\Ag{45}
\def\Ah{46}
\def\Ai{72}
\def\Aj{81}
\def\Ba{59}
\def\Bb{65}
\def\Bc{50}
\def\Bd{64}
\def\Be{67}
\def\Bf{50}
\def\Bg{53}
\def\Bh{55}
\def\Bi{46}
\def\Bj{51}
\def\Ca{61}
\def\Cb{65}
\def\Cc{70}
\def\Cd{75}
\def\Ce{63}
\def\Cf{66}
\def\Cg{63}
\def\Ch{52}
\def\Ci{54}
\def\Cj{50}
\def\Da{52}
\def\Db{55}
\def\Dc{52}
\def\Dd{57}
\def\De{53}
\def\Df{51}
\def\Dg{57}
\def\Dh{56}
\def\Di{54}
\def\Dj{63}

\newcommand{\elements}{
  \Aa,\Ab,\Ac,\Ad,\Ae,\Af,\Ag,\Ah,\Ai,\Aj,
  \Ba,\Bb,\Bc,\Bd,\Be,\Bf,\Bg,\Bh,\Bi,\Bj,
  \Ca,\Cb,\Cc,\Cd,\Ce,\Cf,\Cg,\Ch,\Ci,\Cj,
  \Da,\Db,\Dc,\Dd,\De,\Df,\Dg,\Dh,\Di,\Dj
}

\begin{document}

The numbers that are greater than $50$ are
\countelements{
  \Aa,\Ab,\Ac,\Ad,\Ae,\Af,\Ag,\Ah,\Ai,\Aj,
  \Ba,\Bb,\Bc,\Bd,\Be,\Bf,\Bg,\Bh,\Bi,\Bj,
  \Ca,\Cb,\Cc,\Cd,\Ce,\Cf,\Cg,\Ch,\Ci,\Cj,
  \Da,\Db,\Dc,\Dd,\De,\Df,\Dg,\Dh,\Di,\Dj
}{#1 > 50}

The numbers that are between $52$ and $54$ (inclusive) are
\countelements{\elements}{52 <= #1 <=54}

\end{document}

在此处输入图片描述

相关内容