如何从Tcl列表中删除重复元素?
list is like [this,that,when,what,when,how]
我已经搜索过并找到了lsort unique
,但对我来说并没有起作用。我想从列表中删除“when”。
list is like [this,that,when,what,when,how]
我已经搜索过并找到了lsort unique
,但对我来说并没有起作用。我想从列表中删除“when”。
以下方法对我有效
set myList [list this that when what when how]
lsort -unique $myList
这会返回
how that this what when
你可以将其存储在一个新列表中
set uniqueList [lsort -unique $myList]
你还可以使用字典,其中键必须是唯一的:
set l {this that when what when how}
foreach element $l {dict set tmp $element 1}
set unique [dict keys $tmp]
puts $unique
this that when what how
Glenn Jackman的答案在Tcl 8.6及以上版本上完美运行。
对于Tcl 8.4及以下版本(没有dict命令),您可以使用:
proc list_unique {list} {
array set included_arr [list]
set unique_list [list]
foreach item $list {
if { ![info exists included_arr($item)] } {
set included_arr($item) ""
lappend unique_list $item
}
}
unset included_arr
return $unique_list
}
set list [list this that when what when how]
set unique [list_unique $list]
`set a "this that when what when how"
for {set i 0} {$i < [llength $a]} {incr i} {
set indices [lsearch -all $a [lindex $a $i]]
foreach index $indices {
if {$index != $i} {
set a [lreplace $a $index $index]
}
}
}
`