Grasshopper

algorithmic modeling for Rhino

[Python] Flatten tree with n branches -> 1 branch with n lists

Hi. I am trying to flatten a tree with n branches so that I have a 1 branch with n lists. I came up with something and wanted to know if someone could perhaps tell me whether it's a good idea to do it this way or if it can be done better, differently or safer.

Views: 2006

Replies to This Discussion

Sorry can't help you.
You seem to be using more advanced stuff then what I know (sticky dictionary).

What you have as an output is definitively a python nested list. Grasshopper does not understand what is being exported, that is why it says: "IronPython.RuntimeList".
You could place each of those lists on a separate branch, but not sure if that is what you want ("bol2" being the second output):

import System
import Grasshopper.Kernel.Data as ghp
import Grasshopper.DataTree as ghdt
import scriptcontext as sc

def clear(a,b):
    sc.sticky['branchoflists'] = []
    pass

ghenv.Component.PingDocument += clear
ghenv.Component.SolutionExpired += clear

sc.sticky['branchoflists'].append(lob)

ghenv.Component.ClearData()
bol = sc.sticky['branchoflists']


newTree = ghdt[System.Object]()
for i in range(len(bol)):
    branchL = []
    path = ghp.GH_Path(i)
    for j in range(len(bol[i])):
        branchL.append(bol[i][j])
    newTree.AddRange(branchL, path)
bol2 = newTree

See this post for a suggestion - it's in VB/c# but it still applies:

http://www.grasshopper3d.com/forum/topics/converting-a-list-of-list...

The upper python code works on converting nested lists into data tree, too.


The problem is, that he is trying to use this logic for the purpose of updating his python output gradually, not getting the final output once the component executes the solution.

ah, I misunderstood.

OP doesn't say anything about needing to get the output gradually. If the goal is actually to construct a single branch of python lists as the current script does, this following script does so without relying on multiple solutions. Assumes Data Tree access for x. 

lists = []
for branch in x.Branches:
lists.append(list(branch))
a = lists

He is using the sticky dictionary, so I thought that he might want to use it to gradually output the lists/branches to it.
Seems like I was wrong. Sorry about that.

I usually use list comprehension for converting a DataTree (x) to a nested Python list (a). Like so:

a = [list(i) for i in x.Branches]

that's really nice! I wasn't familiar with that syntax. Python is full of nice surprises

It really is :)

RSS

About

Translate

Search

Photos

  • Add Photos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service