I have this kind of list : { A D C } { D S D } { A S D } { Y D D }
I want to list all the index that have duplicates in the same index of the sublist. For example if I want to serach every "D" at index 2 in sublist, I want to know the index of the list (here 0 and 3)
here is the code :
proc findElement {lst idx value} {
set i 0
foreach sublist $lst {
if {[string equal [lindex $sublist $idx] $value]} {
return $i
}
incr i
}
return -1
}
When i call it findElement $toto 1 D
it returns only 0 !
Why ?
Because you have a return statement when it finds a match when $i = 0.
Try the following which instead returns a list of all the matching indexes
proc findElement {lst idx value} {
set i 0
set return_list [list]
foreach sublist $lst {
puts "i=$i sublist=$sublist"
if {[string equal [lindex $sublist $idx] $value]} {
puts "Found $i"
lappend return_list $i
}
incr i
}
return $return_list
}
You can do a shorter and faster version with lsearch -all -exact -index.
proc findElement {lst idx value} {
return [lsearch -all -exact -index $idx $lst $value]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With