是否有一个命令可以让我获得两个列表的交集(出现在两个列表中的成员)?
例如,如果列表是:
a b c d h
和c e f g h
结果应该是c h
假设您真正拥有的是一个集合(具有唯一元素的列表),您可以使用 tcllib:
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
没有命令,但通常我这样做的方式是在构建一个或多个列表期间缓存元素,以节省时间。例如,给定以下内容:
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
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
}
}