Skip to main content
  1. Posts/

Co-sort multiple python lists

·151 words·1 min

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.

1
2
3
4
5
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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]

Original post on web.archive.org.