Remove duplicate elements from list in Tcl
Asked Answered
tcl
C

4

5

How to remove duplicate element from Tcl list say:

list is like [this,that,when,what,when,how]

I have Googled and have found lsort unique but same is not working for me. I want to remove when from list.

Culp answered 4/12, 2013 at 10:35 Comment(2)
What do you call a "list"?Matted
@user2901871, you have asked many Tcl questions where you do not show that you understand Tcl syntax. The Tcl tutorial will help you quite a bit: tcl.tk/man/tcl8.5/tutorial/tcltutorial.htmlLazy
B
13

The following works for me

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

this returns

how that this what when

which you could store in a new list

set uniqueList [lsort -unique $myList]
Bontebok answered 4/12, 2013 at 11:23 Comment(1)
This one will change the order of the original listGoodhumored
L
9

You could also use an dictionary, where the keys must be unique:

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

That will preserve the order of the elements.

Lazy answered 4/12, 2013 at 13:36 Comment(0)
G
1

glenn jackman's answer work perfectly on Tcl 8.6 and above.

For Tcl 8.4 and below (No dict command). You can use:

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]

This will also preserve the order of the elements and this is the result:

this that when what how

Goodhumored answered 23/2, 2016 at 9:0 Comment(0)
F
0

Another way, if do not wanna use native lsort function.This is what the interviewer asks :)

`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]
        }
    }
}

`

Fatback answered 5/8, 2016 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.