4

I have an issue, which is probably more of an syntax issue, but I have a nested list:

{{11, {1, 2, 3}}, {12, {4, 5, 6}}, {13, {7, 8, 9}}}

I am trying to get:

{{11, 1}, {11, 2}, {11, 3}, {12, 4}, {12, 5}, {12, 6}, ... ,{13, 9}}

I couldn't find anything relating to it in the Documentation Center and I couldn't manage to quickly rearrange this without copious amounts of Transposing and Selecting.

Thank you

MikeLimaOscar
  • 3,456
  • 17
  • 29
J. Joo
  • 107
  • 5

2 Answers2

5
Join @@ Thread /@ {{11, {1, 2, 3}}, {12, {4, 5, 6}}, {13, {7, 8, 9}}}

{{11, 1}, {11, 2}, {11, 3}, {12, 4}, {12, 5}, {12, 6}, {13, 7}, {13, 8}, {13, 9}}

Performance remark

Should you have to process long list, it might be a better strategy to avoid constructing the mixed list

{{11, {1, 2, 3}}, {12, {4, 5, 6}}, {13, {7, 8, 9}}}

but to employ the pure arrays

a = {11, 12, 13}
b = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

because the latter two can be packed.

Here a timing example:

n = 100000;
a = RandomInteger[{1, 1000}, n];
b = RandomInteger[{1, 1000}, {n, 3}];

Your original dataset corresponds to

input = Transpose[{a, b}];

Now the timings:

input = Transpose[{a, b}];
r1 = Join @@ Thread /@ input; // RepeatedTiming // First
r2 = Flatten[
     {Transpose[ConstantArray[a, 3]], b},
     {{2, 3}, {1}}
     ]; // RepeatedTiming // First
r1 == r2

0.11

0.00587

True

You see, the method with Flatten performs almost 20 times faster, mostly because it only involves packed arrays (as input as was as intermediate results).

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
1
Distribute[#, List] & /@ list

{{{11, 1}, {11, 2}, {11, 3}}, {{12, 4}, {12, 5}, {12, 6}}, {{13, 7}, {13, 8}, {13, 9}}}

user1066
  • 17,923
  • 3
  • 31
  • 49