12
$\begingroup$

I have three lists, e.g.

list1 = {{a,b,...}};
list2 = {{1,2},{3,4},...};
list3 = {{x,y},{z,w},...};

and a function

f[x_,y_]:=(* whatever it does *);

I need to get

{{f[a,1],f[a,2],...},{f[b,3],f[b,4],...}}

and

{f[{1,2},{x,y}],f[{3,4},{z,w}],...}

using built-in functions if possible (or in other fast way).

$\endgroup$
2
  • $\begingroup$ For the second, look up MapThread[]. $\endgroup$
    – J. M.'s torpor
    Oct 12 '15 at 13:02
  • $\begingroup$ related: 38023 $\endgroup$
    – Kuba
    Oct 12 '15 at 13:14
13
$\begingroup$

There are many closely related topics but I've failed to find a duplicate.

MapThread[Thread @* f, {First @ list1, list2}]

MapThread[f, {list2, list3}]
{{f[a, 1], f[a, 2]}, {f[b, 3], f[b, 4]}}

{f[{1, 2}, {x, y}], f[{3, 4}, {z, w}]}
$\endgroup$
9
$\begingroup$
l1 = {a, b}; (* one level less*)
l2 = {{1, 2}, {3, 4}};
l3 = {{x, y}, {z, w}};

Transpose[Inner[f, l1, l2, List]]
(* {{f[a, 1], f[a, 2]}, {f[b, 3], f[b, 4]}} *)

Thread[f[l2, l3]]
{f[{1, 2}, {x, y}], f[{3, 4}, {z, w}]}
$\endgroup$
3
$\begingroup$

Data generator

With[{n = 5},
  data1 = Symbol /@ Take[Alphabet[], n];
  data2 = Partition[Range[2 n], 2];]
Column[{data1, data2}]

data

Answer to 1st part

I have a simple mind and like simple solutions, so I would write a helper function that destructures the data.

helper[u_, {m_, n_}] := {f[u, m], f[u, n]}

Then the desired result is given by the simple application of Thread.

Thread[helper[First @ data1, data2]]
{{f[a, 1], f[a, 2]}, {f[b, 3], f[b, 4]}, {f[c, 5], f[c, 6]}, 
 {f[d, 7], f[d, 8]}, {f[e, 9], f[e, 10]}}

As belisarius has pointed out, Thread is also the solution to the 2nd part of the question.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.