I have these two lists, both with the same length in the first dimension:
l1={{a1,a2},{b1,b2},{c1,c2}};
l2={{{1,2,3},{4,5,6}},{{10,11,12},{13,14,15},{16,17,18}},{{19,20,21}}};
And I need mix both to get into this result:
{{a1,a2,1,2,3},{a1,a2,4,5,6},{b1,b2,10,11,12},{b1,b2,13,14,15},
{b1,b2,16,17,18},{c1,c2,19,20,21}}
I have done this code that do the job:
Flatten[MapThread[Function[{a,b},Join[a,#]&/@b][#1,#2]&,{l1,l2}],1]
But I think it could be simpler. Some clue?
Answer
I don't know why no one thought to use ArrayFlatten
:
wizard1[l1_, l2_] := ArrayFlatten @ MapThread[Append, {l1, l2}]
wizard2[l1_, l2_] := ArrayFlatten @ Join[l1, List /@ l2, 2]
Test:
wizard1[l1, l2]
wizard1[l1, l2] === wizard2[l1, l2]
{{a1, a2, 1, 2, 3}, {a1, a2, 4, 5, 6}, {b1, b2, 10, 11, 12},
{b1, b2, 13, 14, 15}, {b1, b2, 16, 17, 18}, {c1, c2, 19, 20, 21}}
True
According to ssch's test suite these functions are also the fastest:
testSpeed[50000, 15]
Comments
Post a Comment