5
$\begingroup$

I work with the following list

data = {{a}, {{a, b}, {a, b}}, {{{a, b, c}}}};

In real, the dataset is much longer and each row has a different structure of having {}

I want to restructure it to:

{{a}, {a, b},  {a, b}, {a, b, c}}

Is this possible using Flatten. If not, what is the easiest way to do this.

A special case is when the data contains DateObjects like:

{{{DateObject[01 - 06 - 2020], "buy", 572.18, 
   DateObject[01 - 06 - 2020], "sell", 570.52}}, { 
  DateObject[01 - 12 - 2020], "buy", 
  616.2}, {DateObject[01 - 01 - 2021], "sell", 
  697.94`}, {DateObject[01 - 02 - 2021], "buy", 
  708.43`}, {DateObject[01 - 03 - 2021], "keep", 709.36`}}
$\endgroup$
5
  • 5
    $\begingroup$ Level[data, {-2}] ? $\endgroup$
    – Ben Izd
    Commented Jun 17, 2021 at 13:42
  • 4
    $\begingroup$ Cases[data, {Except[_List]..}, Infinity] or Cases[data, _List?VectorQ, Infinity] might be what you want. The suggestion by @BenIzd will only work if the elements of you lists are all atomic. $\endgroup$ Commented Jun 17, 2021 at 14:13
  • $\begingroup$ You could add your new test case to the question $\endgroup$
    – mikado
    Commented Jun 17, 2021 at 15:49
  • 1
    $\begingroup$ Use Replace[ReplaceRepeated[data, {{a__}} :> {a}], {a__List} :> a, {1}] for your new test case. $\endgroup$
    – Ben Izd
    Commented Jun 17, 2021 at 16:45
  • 1
    $\begingroup$ also List[data //. {a__List} :> a] and Replace[data, {a__List} :> a, All]? $\endgroup$
    – kglr
    Commented Jun 17, 2021 at 17:10

4 Answers 4

4
$\begingroup$
data = {{a}, {{a, b}, {a, b}}, {{{a, b, c}}}};

Using Cases

Cases[data, {_?AtomQ , ___}, -1]

{{a}, {a, b}, {a, b}, {a, b, c}}

$\endgroup$
3
$\begingroup$

Try this:

Join[Sequence @@ Map[Level[#, {Depth[#] - 2}] &, data]]

(*  {{a}, {a, b}, {a, b}, {a, b, c}}   *)

I am not sure if it will work in more complex cases.

$\endgroup$
3
$\begingroup$
data = {{a}, {{a, b}, {a, b}}, {{{a, b, c}}}};

Cases[data, _?VectorQ, All]

Result:

{{a}, {a, b}, {a, b}, {a, b, c}}

$\endgroup$
1
$\begingroup$
data = {{a}, {{a, b}, {a, b}}, {{{a, b, c}}}};

Using Delete and Nest:

f = Nest[Delete[#, {0}] &, #, Depth[#] - 2] &;

f /@ data

(*{{a}, {a, b}, {a, b}, {a, b, c}}*)
$\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.