5
$\begingroup$

I have a list that looks something like:

d={{{1}},{{2}},{{3},{4}},{{5}},{{1},{8}}}

Is there a generic way to use flatten so that you can selectively target elements within a specific sublist or is another function necessary? The output I'm looking to get is:

finald={{{1}},{{2}},{{3,4}},{{5}},{{1,8}}}
$\endgroup$
8
$\begingroup$
SubsetMap[Map[Transpose], d, {3, 5}]
 {{{1}}, {{2}}, {{3, 4}}, {{5}}, {{1, 8}}}  

Also

SubsetMap[Map[List@*Flatten], d, {3, 5}]

SubsetMap[Map[List@*Apply[Join]], d, {3, 5}]

MapAt[Transpose, d, {{3}, {5}}]
$\endgroup$
7
$\begingroup$
MapAt[{Flatten[#]} &, d, {{3}, {5}}]

(* if you don't know the position, but know the elements *)
MapAt[{Flatten[#]}&, d, 
  Join[
    Position[d, {{3}, {4}}],
    Position[d, {{1}, {8}}]
  ]
]
$\endgroup$
2
  • $\begingroup$ Thank you, is there a generic way to perform this function without specifying the positions? For example I'm working with lists that are variations of "d" so the parts I need to flatten aren't always at position 3 and 5. $\endgroup$
    – D'Angelo
    Jun 16 '20 at 1:04
  • $\begingroup$ I've updated my answer. It will flatten all {{3},{4}} elements and {{1},{8}} elements $\endgroup$
    – flinty
    Jun 16 '20 at 1:10
4
$\begingroup$

Since you want to flatten by pattern rather than position:

d = {{{1}}, {{2}}, {{3}, {4}}, {{5}}, {{1}, {8}}};

toFlat = {{3}, {4}} | {{1}, {8}};

d /. x : toFlat :> Flatten[x]
{{{1}}, {{2}}, {3, 4}, {{5}}, {1, 8}}

Also works with general patterns:

toFlat = {{3 | 1}, _};

d /. x : toFlat :> Flatten[x]
{{{1}}, {{2}}, {3, 4}, {{5}}, {1, 8}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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