2
$\begingroup$

This is a follow up from Splitting a list of lists .

What would be a nice way to split the list

l1 = {1,2,{a,b,c},3,{d,e}}

into

{{1,2,a,3,d},{1,2,a,3,e},{1,2,b,3,d},{1,2,b,3,e},{1,2,c,3,d},{1,2,c,3,e}}

?

$\endgroup$
1

3 Answers 3

5
$\begingroup$

You can use:

Distribute[l1, List]
$\endgroup$
1
  • $\begingroup$ ...thank you for introducing me to Distribute! :) $\endgroup$
    – ubpdqn
    Nov 21, 2014 at 11:55
4
$\begingroup$

Here is an approach:

Tuples[Replace[l1, x_?AtomQ :> {x}, {1}]]

yields:

(*{{1, 2, a, 3, d}, {1, 2, a, 3, e}, {1, 2, b, 3, d}, {1, 2, b, 3, 
  e}, {1, 2, c, 3, d}, {1, 2, c, 3, e}}*)
$\endgroup$
1
$\begingroup$

Just an other one which is not as "simple" as the other answers:

Evaluate@With[{pos = Flatten@Position[l1, _List]}, 
    ReplacePart[l1, Rule @@@ Thread[{pos, Slot /@ Range@Length@pos}]]] & @@@ 
    Tuples[Variables /@ l1 /. {} :> Sequence[]]
{{1, 2, a, 3, d}, {1, 2, a, 3, e}, {1, 2, b, 3, d}, 
 {1, 2, b, 3, e}, {1, 2, c, 3, d}, {1, 2, c, 3, e}}

Which is basically distributing

Tuples[Variables /@ l1 /. {} :> Sequence[]]
{{a, d}, {a, e}, {b, d}, {b, e}, {c, d}, {c, e}}

over

Evaluate@With[{pos = Flatten@Position[l1, _List]}, 
  ReplacePart[l1, Rule @@@ Thread[{pos, Slot /@ Range@Length@pos}]]] &
{1, 2, #1, 3, #2}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.