banj
banj

Reputation: 71

TCL getting the nth item from every list that matches in a list of lists

I am looking for a nice short way to get every nth item from a list of lists if the nested list matches a criteria. So if I have this list:

set x [list [list a 1] [list b 2] [list a 3] [list b 4]]

looking for all the second items in the lists that has "a" as the first item I want to get {1 3}. (The list is a key-value pair, so in short I want all the values of the specified key).

This does the work:

lsearch -all -index 1 -inline -subindices [lsearch -all -index 0 -inline $x a] *

But I am looking for a neater shorter way to do this.

Thanks!

Upvotes: 3

Views: 1095

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137587

With 8.5, I'd advise sticking with what you've got. With Tcl 8.6, you can use lmap:

lmap i $x {lassign $i k v; if {$k ne "a"} continue; set v}
lmap i $x {if {[lindex $i 0] ne "a"} continue {lindex $i 1}}

I'm not sure which one you prefer. (The second is a little longer and a little trickier, but generates better bytecode. The versions with lsearch aren't bytecoded in any version.)

Upvotes: 3

Related Questions