在Tcl中从列表中删除重复元素

5
如何从Tcl列表中删除重复元素?
list is like [this,that,when,what,when,how]

我已经搜索过并找到了lsort unique,但对我来说并没有起作用。我想从列表中删除“when”。


1
你如何称呼一个“列表”? - Johannes Kuhn
@user2901871,你提出了许多 Tcl 的问题,但并没有展示出你对 Tcl 语法的理解。Tcl 教程会对你有很大帮助:http://tcl.tk/man/tcl8.5/tutorial/tcltutorial.html - glenn jackman
4个回答

13

以下方法对我有效

set myList [list this that when what when how]
lsort -unique $myList

这会返回

how that this what when

你可以将其存储在一个新列表中

set uniqueList [lsort -unique $myList]

这个将会改变原始列表的顺序。 - Hazem

9

你还可以使用字典,其中键必须是唯一的:

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

那样可以保持元素的顺序。

1

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]

这也将保留元素的顺序,以下是结果:
这 那 当 什么 如何

0
另一种方法,如果不想使用本地的lsort函数。这就是面试官所问的 :)
`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]
        }
    }
}

`


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接