Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert list of lists to list of tuples?

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?

like image 502
Vignesh Sivam Avatar asked May 30 '15 12:05

Vignesh Sivam


People also ask

How do you make a list of lists in tuples Python?

To convert a list of lists to a list of tuples: Pass the tuple() class and the list of lists to the map() function. The map() function will pass each nested list to the tuple() class. The new list will only contain tuple objects.

How do you split a list into a tuple?

Method #1 : Using map() + split() + tuple() The map function can be used to link the logic to each string, split function is used to split the inner contents of list to different tuple attributes and tuple function performs the task of forming a tuple.

How do you get a list value's tuple form?

Python list of tuples using list comprehension and tuple() method. Python tuple() method along with List Comprehension can be used to form a list of tuples. The tuple() function helps to create tuples from the set of elements passed to it.


2 Answers

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}]
like image 72
Steve Vinoski Avatar answered Oct 02 '22 17:10

Steve Vinoski


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.

like image 37
Pascal Avatar answered Oct 02 '22 15:10

Pascal