Mathematica Asked on April 18, 2021
I an aware of the Partition
command which partitions a list into sublists. I’m curious as to whether there is an efficient way to partition a list several times over in one step. For example, can I turn the list
{1,2,3,4,5,6,7,8}
into the list
{{{1,2},{3,4}},{{5,6},{7,8}}}
through one use of the Partition
command instead of two (or indeed any command). In actual fact, I’ll be going to a list of many levels of nested lists, which is why I’m keen to know the answer. Thanks in advance for any help.
Try ArrayReshape
:
ArrayReshape[{1, 2, 3, 4, 5, 6, 7, 8}, {2, 2, 2}]
{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
or Fold
+ Partition
:
Fold[Partition, Range[8], {2, 2}]
{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
or Nest
+ Partition
:
Nest[Partition[#, 2] &, Range @ 8, 2]
{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
There is also the (undocumented) 6-argument of form of Partition
:
Partition[Range @ 8, 4, 4, 1, {}, Partition[{##}, 2] &]
{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
Correct answer by kglr on April 18, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP