Python list sorting


#1

Say I have a list of cube objects in maya using python.

cubes = [‘cube01’,‘cube02’,‘cube03’]

How would I go about sorting that list based on their translate X value for example. So if-

cube01 translatex = 5
cube02 translatex = 3
cube03 translatex = 10

The list would be sorted to-

cubes = [‘cube02’,‘cube01’,‘cube03’]

This isn’t the exact thing I’m trying to accomplish, but it’s a simple example of what I’m trying to get done.


#2

You could use something like that:

cubes = ['pCube1', 'pCube2', 'pCube3']
#put your cubes into a dictionary with the ty value as keys and the cubes name as values
cubesDict = {mc.getAttr('%s.ty' %i) : i for i in cubes}
#use list comprehension to create a list from the sorted cubesDict
cubesListSorted = [cubesDict[i] for i in sorted(cubesDict)]
#print it :)
print cubesListSorted

#3

Hey Matt thanks for the reply! Yeah I was wondering if a dictionary would work. That’ll be good to know in the future.

I ended up doing it another way in case anyone was interested in an alternative.

I basically used sort with a lambda as a key. Like below, all caps can be replaced with your correct information.

LISTTOSORT.sort(key=lambda pos:mc.getAttr(THEVALUETOSORTWITH))


#4

Little thing to add here:
For dictionaries, dont use potentially non-unique data as keys.
If you have more than one object with the same .ty value, then your dictionary method will fail.


#5

Good to know, thanks for the heads up