Given this input
lst1 = {{a, b, c}, {d, e, f}};
lst2 = {1, 2};
and the goal is to generate this output
{ {{1, a}, {1, b}, {1, c}},
{{2, d}, {2, e}, {2, f}}
}
Perfect candidate for MapThread So I made this diagram first to figure what the function I want to map should be
So the function to use inside MapThread
, needs to also use Map
itself (in order to map each item into the other list). So I came up with this:
lst1 = {{a, b, c}, {d, e, f}};
lst2 = {1, 2};
foo[i_, lst_List] := List[i, #] & /@ lst
MapThread[foo[#1, #2] &, {Range[Length@lst2], lst1}]
(* { {{1,a}, {1,b}, {1,c}}, {{2,d}, {2,e}, {2,f}} } *)
Now here is the question: Is there a way to do the above without having to define an explicit function but using pure function inside MapThread
?
I was getting conflict with #
mapping. This is sort of the thing I was trying to do, but can't get the syntax right
(*invalid, for illustration only *)
MapThread[
Function[{idx, lst},List[idx, #] & /@ lst] & ?? ?? ,{Range[Length@lst2],lst1}]
Or if you know of a better approach to do this, that will be fine as well.
Answer
MapThread[Thread[{##}] &, {lst2, lst1}]
Map[Thread, {lst2, lst1}\[Transpose]]
##
is used so Thread
gets called like Thread[{1, {a, b, c}}]
As MapThread
gives two arguments in this case it is equivalent to Thread[{#1, #2}]&
and Composition[Thread, List]
Comments
Post a Comment