Table/Tree of values

扶醉桌前 提交于 2019-12-01 12:55:38

A large part of what you want to do is either very application-specific or more a kind of object oriented view of data structures and code.

But in a first approximation, to help you, here is a little tool which is for many years in my bag of tricks and will complement Map, MapThread and Partition for your kind of problem:

PartitionAs[k_List, c_List] := 
    Map[Take[k, #] &, 
         FoldList[Last[#1] + {1, #2} &, {1, First[c]}, Rest@c]]

PartitionAllAs[k_List, c_List] := 
    Map[Take[k, #] &, 
       If[Last[Last[#]] < Length[k], 
           Append[#, {Last[Last[#]] + 1, Length[k]}], #] &@
                 FoldList[Last[#1] + {1, #2} &, {1, First[c]}, Rest@c]]

Here is an example of what they do

PartitionAs[{a, b, c, d, e, f, g, h, i, j, k}, {1, 2, 5}]

{{a}, {b, c}, {d, e, f, g, h}}


PartitionAllAs[{a, b, c, d, e, f, g, h, i, j, k}, {1, 2, 5}]

{{a}, {b, c}, {d, e, f, g, h}, {i, j, k}}

They have no checks built-in (they do not test if the list of part lengths you send them is compatible with the list size, etc) so it is up to the calling code to be correct, but they may be handy for your application. Also they are only able to specify one depth of partitioning. One could imagine other ways to specify the partitions and it is not very difficult to build more general tree making routines from a flat list. Tell us if you need this kind of things.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!