2

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?

serenesat
  • 4,611
  • 10
  • 37
  • 53
omer
  • 1,242
  • 4
  • 18
  • 45

3 Answers3

7

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).

Sergei Golovan
  • 611
  • 4
  • 4
1

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.

serenesat
  • 4,611
  • 10
  • 37
  • 53
Muhammad Ali
  • 129
  • 7
0

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.

mrcalvin
  • 3,291
  • 12
  • 18