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?
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.
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.
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.
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}]
I prefer in your case list comprehension because:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With