Sort_list in order


#1

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

#2

@hcmutkhanghaxuan Please format your code; select your code and press this button;

image

What’s the error you get? Post an image Please


#3

Here you go, I edited my code above.


#4

@hcmutkhanghaxuan Thanks.

What error do you get?


#5

@hcmutkhanghaxuan if you want to copy a list you should write:

list_in2=list_in[:]


#6

Why use Python when this can be done with a single node?

image


#7

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

Thanks so much guys!