Reputation: 1440
Say I have a list like this: {{1 2 3} {4 5 6} {7 8 9}}
and I'd like to create a new list made of the first element of each of the nested list: {1 4 7}
. I Know how to do that in a couple of lines using 'foreach', but is that a more elegant way or, better yet, a built-in function that does that?
Upvotes: 2
Views: 8485
Reputation: 129
As you know that you want to search the first element , so that is optimum solution for you to use foreach
. The Complexity will be in your case O(1). As you just need to access the first value on index which is fixed.
Upvotes: 1
Reputation: 3434
As an alternative to using [lmap]
/[lindex]
, re-formulate the problem to one on a flattened, but regular list. That is, accessing the nth (1st, 2nd, ...) element after having flattened the input list of lists:
set a {{1 2 3} {4 5 6} {7 8 9}}
set A [concat {*}$a]; # flattened list: {1 2 3 4 5 6 7 8 9}
lmap {pick drop drop} $A {set pick}
Depending on the layout of the input list, however, the [lmap]
/[lindex]
tactic is likely to outrun the above.
Upvotes: 0
Reputation: 611
If you're using Tcl 8.6 then there's lmap
command which does mapping of a list and can be used for your task:
%set a {{1 2 3} {4 5 6} {7 8 9}}
{1 2 3} {4 5 6} {7 8 9}
%lmap x $a {lindex $x 0}
1 4 7
The lmap
command iterates through the list $a
, assigns the currently processing list item to a given variable (x
in the example) and calls a command (lindex $x 0
in te example).
Upvotes: 7