保留tcl中两个列表中的公共元素并将它们放在结果列表中

时间:2013-06-20 17:43:33

标签: list duplicates tcl

我有两个包含整数的不同长度的列表。 现在列表中有重复项。 查看两个列表时有重复项。 例如

set ListA [list 3 4 9 1 2 10 6 ]
set ListeB [list 34 43 9 12 2 10 61 88 23 48]

是否有一种有效的快速方法来创建一个仅包含原始列表中存在的数字的新列表?在这种情况下:[9 2 10]

我不想使用嵌套循环,因为列表可能很大。我首先考虑对它们进行排序,然后逐个元素地对它们进行比较。然而,只有两个列表具有相同的长度时才有效....

1 个答案:

答案 0 :(得分:2)

请参阅此questiondocumentation here。这适用于Tcl 8.0,仍然适用于8.5(我也非常确定8.6)。

% package require Tcl
% package require struct::set

% set ListA [list 3 4 9 1 2 10 6 ]
% set ListeB [list 34 43 9 12 2 10 61 88 23 48]
% ::struct::set intersect $ListA $ListeB
9 2 10