12

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).

T. Rihacek
  • 511
  • 2
  • 8

3 Answers3

13

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}]}

Kuba
  • 136,707
  • 13
  • 279
  • 740
9
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}]}
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
3

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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257