1
$\begingroup$

I have a function that generates nested lists of the following form:

l1 = {{a1,a2},{{a11,a12},{a21,a22}},{{{a111,a112},{a121,a122}},{{a211,a212},{a221,a222}}},...}
l2 = {{b1,b2,b3},{{b11,b12,b13},{b21,b22,b23},{b31,b32,b33}},...}

So the nested lists contain (d (-1 + d^n))/(-1 + d) elements (where {n,d} = Dimensions@list). If they are flattened, we clearly end up with

l1Flat = {a1, a2, a11, a12, a21, a22, a111, a112, a121, a122, a211, a212, a221, a222, ...}
l2Flat = {b1, b2, b3, b11, b12, b13, b21, b22, b23, b31, b32, b33, ...}

I would like to easily reobtain the original nested list. I am sure it is easy and I am missing something here...

$\endgroup$

1 Answer 1

3
$\begingroup$

If I understand your data structure, such an array might be generated as

d = 2
n = 3
a = RandomInteger[10, ConstantArray[d, #]] & /@ Range[n]
aflat = Flatten[a]

It could then be "unflatted" as

aparts = Internal`PartitionRagged[aflat, d^# & /@ Range[n]]
MapIndexed[Nest[Function[lst, Partition[lst, d]], #1, First@#2 - 1] &, aparts]
$\endgroup$
1
  • 2
    $\begingroup$ Recent versions of Mathematica are shipped with TakeList with the same functionality as Internal`PartitionRagged. Based on my experience, Internal`PartitionRagged is often faster than TakeList. $\endgroup$ Dec 6, 2018 at 21:47

Your Answer

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

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