Thursday, 8 March 2012

co-sort multiple python lists

I have written a small function to sort multiple lists. The values are sorted according to the values in the first list first, then the second etc. It can take any number of lists and returns the same number.


def cosort(*lsts):
 """Takes a any number of lists and sorts them based on the values of the first list."""
 tmp = zip(*lsts)
 tmp.sort()
 return zip(*tmp)

Little testing script:


from random import shuffle

def cosort(*lsts):
 """Takes a few lists and sorts them based on the values of the first list."""
 tmp = zip(*lsts)
 tmp.sort()
 return zip(*tmp)

a = range(10)
b = ['a','b','c','d','e','f','g','h','i','j']
c = ['j','i','h','g','f','e','d','c','b','a']

shuffle(a)

for i in range(len(a)):
 print a[i],b[i],c[i]

a,b,c = cosort(a,b,c)

print 
for i in range(len(a)):
 print a[i],b[i],c[i]

No comments:

Post a Comment