Message Boards Message Boards

3 Replies
4 Total Likes
View groups...
Share this post:

How to pair corresponding elements in a list?

Posted 10 years ago
It's tough to explain what I want to do in words, so I'll explain with examples. What is the easiest way to create a function that does the following:
in[1]: function[{{a1, b1},{a2, b2}}]
out[1]: {{a1, a2}, {b1, b2}}

in[2]: function[{a1, b1, c1, d1}, {a2, b2, c2, d2}]
out[2]: {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}

in[3]: function[{{a1, b1},{a2,b2},{a3,b3}}]
out[3]: {{a1, a2, a3}, {b1, b2, b3}}
Essentially I want to group the corrisponding elements of the seperate sublists, to create a new set of sublists.

Any help is greatly appreciated.
POSTED BY: Mitchell Clarke
3 Replies
I think you are looking for MapThread in this case:
POSTED BY: Arnoud Buzing
MapThread is a very good choice for generalized operations, when you not only pairing but also applying a function to pairs. In your simpler case you can also use Thread and Transpose (see blow). Relations between MapThread, Thread, and Transpose are discussed here.
 In[1]:= Transpose[{{a1, b1}, {a2, b2}, {a3, b3}}]
 Out[1]= {{a1, a2, a3}, {b1, b2, b3}}
 In[2]:= Thread[{{a1, b1}, {a2, b2}, {a3, b3}}]
 Out[2]= {{a1, a2, a3}, {b1, b2, b3}}
 In[3]:= Transpose[{{a1, b1, c1, d1}, {a2, b2, c2, d2}}]
 Out[3]= {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}
In[4]:= Thread[{{a1, b1, c1, d1}, {a2, b2, c2, d2}}]
Out[4]= {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}

In[5]:= MapThread[List, {{a, b, c}, {x, y, z}}]
Out[5]= {{a, x}, {b, y}, {c, z}}
POSTED BY: Vitaliy Kaurov
Posted 10 years ago
Transpose does exactly what you want:
Transpose[{{a1, b1}, {a2, b2}}]
Transpose[{{a1, b1, c1, d1}, {a2, b2, c2, d2}}]
Transpose[{{a1, b1}, {a2, b2}, {a3, b3}}]

Out[14]= {{a1, a2}, {b1, b2}}
Out[15]= {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}
Out[16]= {{a1, a2, a3}, {b1, b2, b3}}
POSTED BY: Markus Schopfer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract