Non uniform Riffle of two lists
x = {b1, b2};
y = {{a1, a2}, {a3, a4}, {a5, a6}};
(As suggested in the comments by user1066)
Inner[{#2, #1}&, y, x, List]
$\left( \begin{array}{cc} \{\text{b1},\text{a1}\} & \{\text{b2},\text{a2}\} \\ \{\text{b1},\text{a3}\} & \{\text{b2},\text{a4}\} \\ \{\text{b1},\text{a5}\} & \{\text{b2},\text{a6}\} \\ \end{array} \right)$
My earlier solution:
Inner[Reverse@*List, y, x, List]
Timing comparisons:
i1 = First@RepeatedTiming[ai1 = Inner[{#2, #1} &, y, x, List]];
i2 = First@RepeatedTiming[ai2 = Inner[Reverse@*List, y, x, List]];
t = First@RepeatedTiming[at = Transpose[{x, #}] & /@ y];
{i2, t}/i1
{1.54407, 2.7154}
It gives a 1.5x speed up, and 2.7x compared to using Transpose
.
ai1 == ai2 == at
True
as suggested by @J.M. (who gets all the credit) there is in fact a very simple solution (as I feared! :-) ):
Transpose[{{b1, b2}, #}] & /@ {{a1, a2}, {a3, a4}, {a5, a6}}
Why it works
Well, it seems obvious a posteriori ( :-) ) especially since JM's solution is elegant and simple.
The mapping takes in turn {a1, a2}
, {a3, a4}
...
and applies {{b1, b2}, #}&
to each list
so that we have a list of
{{b1, b2},{a1, a2}}, {{b1, b2},{a3, a4}}...
Thanks to the Transpose
it becomes
{{b1, a1}, {b2, a2}}, {{b1, a3}, {b2, a4}}...
Hence the result.
Postscript
My own clumsy solution arose because I failed to realise that the length of {b1,b2}
was always 2.
How about something like this?
x = {b1, b2};
y = {{a1, a2}, {a3, a4}, {a5, a6}};
z = {{{b1, a1}, {b2, a2}}, {{b1, a3}, {b2, a4}}, {{b1, a5}, {b2,a6}}};
Partition[#, 2] & /@ Riffle @@@ Table[{x, k}, {k, y}]
%==z
{{{b1, a1}, {b2, a2}}, {{b1, a3}, {b2, a4}}, {{b1, a5}, {b2, a6}}}
True
The first step:
t = Table[{x, k}, {k, y}]
{{{b1, b2}, {a1, a2}}, {{b1, b2}, {a3, a4}}, {{b1, b2}, {a5, a6}}}
The second step:
Riffle@@@ t
{{b1, a1, b2, a2}, {b1, a3, b2, a4}, {b1, a5, b2, a6}}
Then all that's needed is to Partition
each sublist. For example,
Partition[{{b1, a1, b2, a2},2]
{{b1,a1},{b2,a2}}