Table/Tree of values

后端 未结 1 1984
借酒劲吻你
借酒劲吻你 2021-01-16 04:33

My question:

Is there a way to create a tree of values? Something like the output of the command TreeForm, but with values in the nodes?

相关标签:
1条回答
  • 2021-01-16 04:52

    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.

    0 讨论(0)
提交回复
热议问题