Hi everyone, I’m trying to use python script to sort list of number into many list containing the same number. For example: I have a input list {1,1,2,3,4,4,5} and the output is {1,1},{2},{3},{4,4},{5}. But my python code seems doesn’t work. This my python script, could you guys help me? Thanks
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
clr.AddReference('DSCoreNodes')
from DSCore import *
#The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN
list_in=IN[0]
all=[]
while len(list_in) >= 2:
list_in2=list_in
sub_list=[]
for i in reversed(range(0,len(list_in2))):
if list_in2[i] == list_in2[len(list_in2)-1]:
sub_list.append(list_in2[i])
del list_in[i]
else:
pass
all.append(sub_list)
#Assign your output to the OUT variable.
OUT = all
@hcmutkhanghaxuan Please format your code; select your code and press this button;
What’s the error you get? Post an image Please
Here you go, I edited my code above.
@hcmutkhanghaxuan Thanks.
What error do you get?
@hcmutkhanghaxuan if you want to copy a list you should write:
list_in2=list_in[:]
Why use Python when this can be done with a single node?
4 Likes
As @Jonathan.Olesen mentioned, this is very simple to achieve inside of nodes, but if you still wish to use Python for this, I would achieve it the following way:
inList = IN[0]
uniqueList = set(inList)
OUT = [ [ item for item in inList if item == unique ] for unique in uniqueList ]
This uses the ‘set’ function that, in essence, creates a Unique List. We then use ‘List Comprehensions’ to iterate across our loops.
These are baseline functions inside of Python - so we don’t need to import anything!
If you wish to have a reversed list (Not sure if so - but see it in your code), you do the following:
inList = IN[0]
uniqueList = set(inList)
reversed = sorted(uniqueList, reverse = True)
OUT = [ [ item for item in inList if item == unique ] for unique in reversed ]
8 Likes