
如何取得datatool
資料庫中特定列的所有不同值?範例是將下表讀入datatool
資料庫:
Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
現在我想獲得Xcity, Ytown,Ztington
該資料庫中所有城鎮 ( ) 和該資料庫中所有年齡 ( 20,30,40
) 的列表,沒有重複項,我可以將其儲存在巨集/任何內容中,以便日後使用datatool
或重複使用pgffor
。
答案1
datatool
有一個名為的宏\DTLifinlist
,可以檢查某個元素是否在給定的逗號分隔清單中,因此可以在建立所有城鎮或年齡的清單時使用它,如下所示:
\documentclass{article}
\usepackage{etoolbox}
\usepackage{datatool}
\begin{filecontents}{test.csv}
Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
\end{filecontents}
\DTLloaddb{data}{test.csv}
\begin{document}
\newcommand*{\uniquetowns}{}
\newcommand*{\uniqueages}{}
\DTLforeach*{data}{\Town=Town,\Age=Age}{%
\expandafter\DTLifinlist\expandafter{\Town}{\uniquetowns}%
{}% do nothing, already in list
{% add to list
\ifdefempty{\uniquetowns}%
{\let\uniquetowns\Town}% first element of list
{% append to list
\eappto\uniquetowns{,\Town}%
}%
}%
% Similarly for age
\expandafter\DTLifinlist\expandafter{\Age}{\uniqueages}%
{}% do nothing, already in list
{% add to list
\ifdefempty{\uniqueages}%
{\let\uniqueages\Age}% first element of list
{% append to list
\eappto\uniqueages{,\Age}%
}%
}%
}
List of unique towns: \uniquetowns.
List of unique ages: \uniqueages.
\end{document}
結果: