在tcl中找到两个列表的交集

时间:2012-08-19 14:19:21

标签: tcl

是否有一个命令可以让我获得两个列表的交集(两个列表中的成员)?

例如,如果列表是:

a b c d hc e f g h

结果应为c h

3 个答案:

答案 0 :(得分:7)

假设你真正拥有的是一个集合(具有唯一元素的列表),你可以使用tcllib:

::struct::set intersect ? set1... ?

package require Tcl 8.0
package require struct::set

set list1 {a b c d h}
set list2 {c e f g h}
::struct::set intersect $list1 $list2
> c h

答案 1 :(得分:4)

没有命令,但通常我这样做的方式是在一个或多个列表的构造期间缓存元素,以节省时间。例如,给出以下内容:

foreach x {a b c d h} {
    lappend list_x $x
}

foreach y {c e f g h} {
    lappend list_y $y
}

我想补充一下:

foreach x {a b c d h} {
    lappend list_x $x
    set cache($x) 1
}

foreach y {c e f g h} {
    lappend list_y $y
    if {[info exists cache($y)]} {
        lappend list_xy $y
    }
}

puts $list_xy

输出:

c h

答案 2 :(得分:2)

package require Tcl 8.5
set a {1 2 3 4 5}
set b {3 4 5 6 7}
set intersect [list]

foreach elem $a {
    if {$elem in $b} {
        lappend intersect $elem
    }
}