How can I sort all levels except the innermost level? The number of levels is unknown. For example:
list = {{{d, c}, {b, a}}, {{4, 3}, {2, 1}}}
If we needed to sort all levels, it would be easy to do expr /. List :> Composition[Sort, List]
, but that is not the case here.
I don't want to change the order of the innermost lists. For example, keep {d, c}
as it is, not {c, d}
, and similarly for other innermost lists. So the expected result in this case would be {{{2, 1}, {4, 3}}, {{b, a}, {d, c}}}
.
Flatten[list, 1] // Sort
evaluates to{{2, 1}, {4, 3}, {b, a}, {d, c}}
$\endgroup${{{a, b}, {c, d}}, {{1, 2}, {3, 4}}}
? Do I understand properly? $\endgroup${d, c}
as it is, not{c,d}
, and similarly for others in the innermost. So the expected result in this case would be{{{2, 1}, {4, 3}}, {{b, a}, {d, c}}}
. $\endgroup$Map[Sort, list, {0, Depth[list] - 3}]]
do what you want? This evaluates to:{{{2, 1}, {4, 3}}, {{b, a}, {d, c}}}
$\endgroup$