5

What's the best way to convert a list such as [[1,2,3],[a,b,c],[4,5,6]] to a list of tuples like this:

[{1,a,4},{2,b,5},{3,c,6}]

where tuple N is composed of the Nth element from each of the three sublists? Should I use a tail recursive function, a list comprehension, or some other approach?

Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46
Vignesh Sivam
  • 75
  • 1
  • 8

4 Answers4

7

Just use the standard lists:zip3/3 function:

1> [L1,L2,L3] = [[1,2,3],[a,b,c],[4,5,6]].
[[1,2,3],[a,b,c],[4,5,6]]
2> lists:zip3(L1,L2,L3).
[{1,a,4},{2,b,5},{3,c,6}]

Or if you'd prefer to avoid extracting the individual lists:

3> apply(lists, zip3, [[1,2,3],[a,b,c],[4,5,6]]).
[{1,a,4},{2,b,5},{3,c,6}]
Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46
4

I prefer in your case list comprehension because:

  • it is a short line of code, easy to read,
  • it doesn't need a helper function, so the operation done is clearly visible.

    L_of_tuple = [list_to_tuple(X) || X <- L_of_list].

If this transformation has to be done in many places, it is better to write it in a separate function, and then any solution (even body recursion with caution) is good for me.

Pascal
  • 13,977
  • 2
  • 24
  • 32
1

One elegant solution can be

lol2lot([[]|_]) -> [];
lol2lot(LoL) ->
    [ list_to_tuple([hd(L) || L <- LoL]) | lol2lot([tl(L) || L <- LoL]) ].
Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
0

For example so:

L =  [[1,2,3],[a,b,c],[4,5,6]].
Size = length(L).
T = [fun(I)->list_to_tuple([lists:nth(I,lists:nth(J,L)) ||J<-lists:seq(1,Size)]) end(I) || I<-lists:seq(1,Size)].