GhPython count lines by length

I’m trying to make a Python script that counts a a set of lines according to their length (e.g. 2 lines < 3’-0", 5 lines between 3’ and 4’ etc.)

The above code works, but I’m trying to make a versions that adapts the ranges in whole foot increments, regardless of the size of the input lines.

Clearly, a for loop inside a for loop won’t work. I need to set each size range as an if statement. (very beginner w/Python)

I’ve attached the .gh definition for reference (“Python open” is the version i"m working on). (19.5 KB)

Any help would be appreciated!


I have no clue about imperial stuff, since I come from the old world - which already is weird, right - but by whole foot increments do you mean a range from 0 to 1, 1.1 to 2, 2.1 to 3, etc. that you want to compare your line lengths against?

Yes, that’s correct. The units don’t really matter. For example:

Line1 = 3.5
Line2 = 4.3
Line3 = 3.1
Line4 = 5.7

(2) lines are 3<x<4
(1) line is 4<x5
(1) line is 5<x<6

This is what the first script does. The issue is that I have to know the terms _ for <x< before inputting the lines. The script I’m trying to create looks at the longest item in the input set, and creates evenly incremented groups to separate the items.



Hi Nathan,

You can for instance do something like this:

from collections import OrderedDict
from ghpythonlib import treehelpers

def round_down(x):
    """Returns an integer rounded down to the nearest ten 
        (e.g. 1.34: 0, 42: 40, etc.)."""
    return int(round(x + 5.1, -1) - 10) 

groups = OrderedDict()  # maps the curve indices and lengths to size range starts

for i, crv in enumerate(Curves):
        len = crv.GetLength()
        start = round_down(len)  # size range start
        if start not in groups.keys():
            groups[start] = []  # create an empty range
        groups[start].append( (i, len) )  # map curve index to length

# Outputs
Sizes = treehelpers.list_to_tree( [[s] for s in groups.keys()] )
Indices = treehelpers.list_to_tree( [[i for i, _ in data] for data in groups.values()] ) (20.0 KB)


This is great! Sorting these into the indices with the single output works well; from here I can just count the list length of each of the indices.

I’m still learning to use GhPython and I see a lot of scripts using the TreeHelpers; I’ll look into this further as I learn.

Thanks for the help!

Exactly, and the Sizes output gives you the start of the size range that the corresponding indices of curves belong to. I forgot to mention before that you can easily get the end of the range by adding 9.99 to the start.

The treehelpers module is handy, because it easily lets you convert between nested Python lists and Grasshopper trees and vis versa. You can output nested lists from the GHPython component, but other components aren’t able to handle those, since Grasshopper works with data trees instead (which are a very similar concept). Outputting flat lists isn’t a problem though.

1 Like