Operation between a datatree and list in python

math between datatree and list.gh (6.5 KB)

I´m working on a code in python with two lists as inputs. One of these lists is transformed in Datatree inside the code and then, I´m trying to do a math operation between the list and the data tree without success. The output needs to be a data tree with a holistic result. It is such a basic code. I know that is easy to do setting the graph on the input, but I really want to solve this in python.

Thank you!

on line 38, you cannot index items into a DataTree object with the brakcets
instead try this:
a = abs((m.sin(G.Branches[i][0])*m.pow(b[i],2)))

of course you’ll have to handle list length mismatch.

Hello Will_Wang,
Thank you for your reply. I had tried some options, and nothing works.
When I specify the Branches, I get the message: “Argument out of range exception”.

as i mentioned, you’d have to manage the mismatch in list length. y input has more items than x. if you want the grasshopper list matching, you can put in a conditional and always match the last of x to the extras in y

if i > len(x)-1:
    item_in_x = b[-1]
    item_in_x = b[i]

Hi Natal,

I had also struggled with data trees, so I’ve written a utility library to deal with them.
Attached is the solution. You can download the library from food4Rhino.

For any function that takes Data Trees as input, no need to loop through anything, simply decorate it with @TreeHandler. TreeHandler will do all the heavy lifting and return results identical to those returned by any native Grasshopper component. For instance, if any one of {arg1, arg2} is a Data Tree, do the following:

def func(arg1, arg2, access=["access_type", "access_type"]):

The access_type is either item or list, depending on whether your function takes a single item or a list as an argument. You must include the access argument for TreeHandler to work.

Hopefully it will simplify your process whenever you need to deal with data trees. Find detail instructions and tutorial links on food4Rhino.

math between datatree and list.gh (11.0 KB)

1 Like