8
$\begingroup$

I would like to map a function that takes as an argument a list in a list of lists and an element of the list of lists. So for example, this is my list of lists:

{{4,1}, {3,1,1}, {2,2,1}}

I would like to map the function to the list of lists to obtain the following outcome:

{ {f[{4,1},4], f[{4,1},1]}, {f[{3,1,1},3}], f[{3,1,1},1], f[{3,1,1},1] }, {f[{2,2,1},2], f[{2,2,1},2], f[{2,2,1},1]}

I would appreciate it if someone could tell me how to do it. Thank you in advance!

$\endgroup$
7
$\begingroup$
lst = {{4, 1}, {3, 1, 1}, {2, 2, 1}};
Table[Table[f[i, j], {j, i}], {i, lst}]

{{f[{4, 1}, 4], f[{4, 1}, 1]}, {f[{3, 1, 1}, 3], f[{3, 1, 1}, 1], f[{3, 1, 1}, 1]}, {f[{2, 2, 1}, 2], f[{2, 2, 1}, 2], f[{2, 2, 1}, 1]}}

$\endgroup$
  • 2
    $\begingroup$ +1. also: Table[f[i, j], {i, lst}, {j, i}] $\endgroup$ – WReach Sep 2 '19 at 6:12
  • $\begingroup$ @WReach Yes, good point! $\endgroup$ – MelaGo Sep 4 '19 at 0:13
7
$\begingroup$

I like the techniques in the other answers (particularly the Table approach in the answer by MelaGo), but here are a few other options to add to the mix...

Given:

$list = {{4,1}, {3,1,1}, {2,2,1}};

Then any of the following expressions yield the desired result:

Curry[f, 2][#] /@ # & /@ $list

or

Cases[$list, l_ :> (f[l, #] & /@ l)]

or

Replace[$list, l_ :> (f[l, #] & /@ l), {1}]

or

MapIndexed[f[$list[[#2[[1]]]], #] &, $list, {2}]

or

ReplacePart[$list, {i_, j_} :> f[$list[[i]], $list[[i, j]]]]
$\endgroup$
7
$\begingroup$
ClearAll[g1,  f]
g1 = Function[x, f[x, #] & /@ x]

lst = {{4, 1}, {3, 1, 1}, {2, 2, 1}};

g1 /@ lst

{{f[{4, 1}, 4], f[{4, 1}, 1]},
{f[{3, 1, 1}, 3], f[{3, 1, 1}, 1], f[{3, 1, 1}, 1]},
{f[{2, 2, 1}, 2], f[{2, 2, 1}, 2], f[{2, 2, 1}, 1]}}

Also

ClearAll[g2, g3, g4]

g2[x_]:= Map[f[x, #] &] @ x
g2 /@ lst


g3 = Thread[f[#, #], List, {2}] & 
g3 /@ lst

g4[x_, y_] := f[x, #] & /@ y
g4[#, #] & /@ lst
$\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.