GhPython : list partition

Hello i tried list partition with ghpythonlib.components but didn’t work,
what is the problem and is there another method to do it ?

import rhinoscriptsyntax as rs
import ghpythonlib.components as ghc
import Rhino.Geometry as rg

list = ['a','b','c','d','e','f']
#num = [2,3,1]
num = 2
a = ghc.PartitionList(list,num)
1 Like

Hello Seghier,

I don’t really know what’s happening with PartionList, but a quick workaround would be a rather simple function that makes use of list splicing, like so:

from ghpythonlib import treehelpers

def split(lt, size=2, out_tree=False):
    nested_lt = []

    while len(lt) > size:
        seg = lt[:size]
        lt   = lt[size:]

    if not out_tree:
        return nested_lt

    return treehelpers.list_to_tree(nested_lt)

Have a nice Sunday!

1 Like

Thank you @diff-arch, this work fine with one number , but i need a list of numbers (size of partitions)
#num = [2,3,1], like the original component

You’re welcome. :slight_smile:

Oh ok, I guess I confused Partition with Split somehow!

Check this out:

I’ve tested the script and it seems to work exactly like the vanilla component!

from ghpythonlib import treehelpers

def partition(lt, size=[2,3,2], tree_out=False):
    """Partitions a list into sub-lists.
        lt: A list to partition
        size: Optional list of partition sizes
        tree_out: Optional, if True a tree is returned,
                  by default a nested list is put out. 
        A partioned list or tree.
    nested_lt = []
    n = 0
    while len(lt) > size[n]:
        sub_lt = lt[:size[n]]
        lt = lt[size[n]:]
        if n == len(size)-1:
            n = 0
            n += 1
    if tree_out:
        return treehelpers.list_to_tree(nested_lt)
    return nested_lt

C = partition(L, S, True)

One thing to consider is that you always need to input a list of sizes, even if you want a regular partition rhythm (e.g. [ [0, 1], [2, 3], [4, 5], [6, 7] ]), you pass in the single size (e.g. 2) as a list (e.g. [2]) ! (4.5 KB)


Thank you :slight_smile:
I will try that

Hi guys,

you can get ghpythonlib.components to do what you are after.

Be default, and always in Rhino 5, ghpythonlib flattens results that are given as trees. This was done for simplicity, but it turned out that sometimes trees are also useful. For example, in this case.

You can use the trees variable to get access to all trees-aware functions. (8.8 KB)



Giulio Piacentino
for Robert McNeel & Associates


Thank you very much Giulio , works fine

Super helpful function! Thank you