2
$\begingroup$

Say I have two lists,

list1 = {{a, b}, {c, d}}
list2 = {{x, y, z},{x1, y1, z1}}

and I want to map a function f over them to produce

{{f[x, {a, b}], f[y, {a,b}], f[z, {a,b}]},{f[x1, {c, d}], f[y1, {c, d}], f[z1, {c, d}]}

I tried some Mappings, but it seems really complex thing.
Is it possible to generate? Thank you.

$\endgroup$
1
  • $\begingroup$ related topics: 96803, 38023 $\endgroup$
    – Kuba
    May 2 '17 at 14:48
2
$\begingroup$

Modified answer from a closely related topic:

How to use Map inside MapThread?

MapThread[Function[{u, b}, f[#, b] & /@ u], {list2, list1}]
{
 {f[x, {a, b}], f[y, {a, b}], f[z, {a, b}]}, 
 {f[x1, {c, d}], f[y1, {c, d}], f[z1, {c, d}]}
}
$\endgroup$
0
1
$\begingroup$

This is on of those cases where an ordinary Table loop is by far the easiest solution:

Table[f[#,list1[[i]]]&/@list2[[i]],{i,2}]

Alternatively, you can use MapIndexed

MapIndexed[
 f[#1,list1[[#2[[1]]]]]&,
 list2,
 {2}
]
$\endgroup$
1
  • $\begingroup$ It's all about the speed, as my real lists are really big. Thank you. $\endgroup$ May 2 '17 at 14:54
1
$\begingroup$
Map[Function[arg, f[arg, #1}]], #2] & @@@ Transpose[{list1, list2}]

or, more similar to Kuba's answer

MapThread[Map[Function[arg, f[arg, #1]], #2] &, {list1, list2}]

both yielding

{{f[x, {a, b}], f[y, {a, b}], f[z, {a, b}]},
 {f[x1, {c, d}], f[y1, {c, d}], f[z1, {c, d}]}}
$\endgroup$
0
$\begingroup$

Ok, it's solved with Distribute.

Distribute[f[{#1}, #2], 
   List] & @@@ {{list2[[1]], list1[[1]]}, {list2[[2]], list1[[2]]}}
$\endgroup$
0

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.