import collections
def flattenList(unflattened_list):
if isinstance(unflattened_list,collections.Iterable):
return [sub_element for element in unflattened_list for sub_element in flattenList(element)]
else:
return [unflattened_list]
OUT = flattenList(IN[0])
Traceback (most recent call last):
File “”, line 15, in
File “”, line 13, in flat
TypeError: iteration over non-sequence of type Point<<
Same warning error for the other one too.
I tried loads of variations of loops and stuff and none worked.
mellouze’s solution does though… If anyone has an explanation why I’d be interested as I’m obviously still a total noob.
def flat(l):
return [item for sublist in l for item in sublist]
Take l as entry (l is supposed to be a list)
Return a list constructed as such : An enumeration of all the item contained in all the sublist of l.
Here, each object named sublist is required to be an iterable (e.g. a list). If called, the function will try to iterate over each sublist item. In your case, you are feeding a list l that contains both points and lists of points. The function will successfully iterate on all the lists of points, but will return an error when it will try to iterate on the points (which is the error you quote in your last post).
def flattenList(l):
if isinstance(l,collections.Iterable):
return [item for sublist in l for item in flattenList(sublist)]
else:
return [l]
Here, the function is a bit more complex. (I changed the name of the variables to match the one of the previous function)
Given a variable l, the function will first check if it is an instance of collections.Iterable, which essentially dictates if Python will be able to iterate over it.
If the object l is an iterable (meaning that in our case, it is a list), the function will return something similar to @solamour’s function. However, Python will not iterate over sublist but over flattenList(sublist) : as you may notice, the function calls itself. In that case, Python will first apply flattenList to sublist, then will continue to iterate.
If the object l is not an iterable (e.g. it’s a Point), Python will return a list composed only of l.
I’ve only been learning python since May, I’ve come across recursive functions but my knowledge is still pretty shaky. In fact I’m still struggling with functions in general.
To be honest, I only copied the answer that was given here.
I guess that in this case, isintance(l,list) is sufficient, but if you would want to flatten iterables that are not list, you would have to use isinstance(l,collections.Iterable).
In case there are sublists inside sublist and I want to flatten to the first sublist, how that would be?
the result asked would be like the input list of this example, with OOTB nodes would be flatten to list level 2 but no idea in python.