4
$\begingroup$

I have a problem with nested lists. For example, i have this list:

solution = {{{{{18, 11, 8}, {17, 12, 2}}, {{17, 12, 11}, {18, 8, 2}}}, {{{{17, 11, 8}, {18, 12, 2}}, {{18, 12, 8}, {17, 11, 2}}}, {{18, 12, 11}, {17, 8, 2}}}}, {{18, 17}, {12, 11, 8, 2}}}

I would like to simplify this nested list into list of lists:

simplified = {{{18, 11, 8}, {17, 12, 2}} , {{17, 12, 11}, {18, 8, 2}}, ...}

How can it be done? I used some ArrayFlatten, but this didn't help me.

Thank you for solution, i am trying to understand this language.

$\endgroup$
3
  • $\begingroup$ Please add the "rules" by which the list is transformed. Readers should not have to decode the meaning from the example. $\endgroup$
    – ciao
    Commented Sep 2, 2020 at 23:48
  • 1
    $\begingroup$ In the process of Nest you can add Flatten to avoid too many {}, rewrite your oiginal code. $\endgroup$
    – cvgmt
    Commented Sep 2, 2020 at 23:52
  • 1
    $\begingroup$ Flatten[solution, 2] $\endgroup$ Commented Sep 3, 2020 at 5:08

3 Answers 3

7
$\begingroup$
Cases[solution, {{__Integer}..}, All]
{{{18, 11, 8}, {17, 12, 2}}, {{17, 12, 11}, {18, 8, 2}},
 {{17, 11, 8}, {18, 12, 2}}, {{18, 12, 8}, {17, 11, 2}}, 
 {{18, 12, 11}, {17, 8, 2}}, {{18, 17}, {12, 11, 8, 2}}}

If the target lists contain exactly two sublists of integers, you can also use

Partition[#, 2] & @ Cases[solution, {__Integer}, All]

Update: Few additional methods:

Level[solution, {-3}]

Fold[FlattenAt, solution, {1, 2, 2, 1}] (* inspired by cvgmt's answer *)

Fold[Delete, solution, Thread[{{1, 2, 2, 1}, 0}]]

Fold[MapAt[Splice,##]&, solution, {1, 2, 2, 1}]
$\endgroup$
2
$\begingroup$

It must be have an elegant way which I could not found at that moment.

solution = {{{{{18, 11, 8}, {17, 12, 2}}, {{17, 12, 11}, {18, 8, 2}}}, {{{{17, 11, 8}, {18, 12, 2}}, {{18, 12, 8}, {17, 11, 2}}}, {{18, 12, 11}, {17, 8, 2}}}}, {{18, 17}, {12, 11, 8, 2}}};
solution//TreeForm
simplified =FlattenAt[1]@
  FlattenAt[2]@FlattenAt[2]@FlattenAt[1]@solution
simplified//TreeForm

enter image description here enter image description here

$\endgroup$
-1
$\begingroup$

If I understand correctly, you are trying to get rid of the two outermost braces. This can simply be done by:

solution = {{{{{18, 11, 8}, {17, 12, 2}}, {{17, 12, 11}, {18, 8, 2}}}, {{{{17, 11, 8}, {18, 12, 2}}, {{18, 12, 8}, {17, 11, 2}}}, {{18, 12, 11}, {17, 8, 2}}}}, {{18, 17}, {12, 11, 8, 2}}}

Flatten[solution, 2 ]
$\endgroup$
1
  • $\begingroup$ This answer would be better if you show the actual code that could be used, in a code-block, along with a depiction (usually the output of the code being ran) of the result of using said code. $\endgroup$ Commented Sep 4, 2020 at 1:34

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.