Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pair lists to create tuples in order

I'd like to combine two lists. If I have the following two lists: {a,b,c,d} and {1,2,3,4} what do I need to do so that I get {{a,1}, {b,2}, {c,3}, {d,4}}?

like image 1000
Martijn Avatar asked Mar 20 '11 19:03

Martijn


People also ask

How do you order a list of tuples?

In python, to sort list of tuples by the first element in descending order, we have to use the sort() method with the parameter ” (reverse=True) “ which will sort the elements in descending order.

How do I turn a two list into a tuple?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.


2 Answers

Here is one way:

Transpose[{{a, b, c, d}, {1, 2, 3, 4}}] 
like image 104
Leonid Shifrin Avatar answered Sep 21 '22 06:09

Leonid Shifrin


An esoteric method is Flatten, which (from the Help Section on Flatten) also allows Transpose of a 'ragged' array.

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

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

like image 43
681234 Avatar answered Sep 21 '22 06:09

681234