[Tutor] Sorting more than one list

Kent Johnson kent37 at tds.net
Thu Mar 31 01:28:53 CEST 2005


Diego Galho Prestes wrote:
> Hi!
> 
> I need to sort 4 lists but I need that they make the "sort together".
> I'll sort just one but when I change the position of the items of the
> 1st list I have to change the positions of the other 3 lists. Can I do
> this just using the sort() method of the list object?

You can zip the lists together into a single list of 4-tuples. Sort this list and then use zip() 
again to create the three original lists. Here is an example using just three lists:

  >>> a=[2,1,4,3]
  >>> b=[1,2,3,4]
  >>> c=[5,6,7,8]
  >>> together = zip(a,b,c)
  >>> together
[(2, 1, 5), (1, 2, 6), (4, 3, 7), (3, 4, 8)]
  >>> together.sort()
  >>> together
[(1, 2, 6), (2, 1, 5), (3, 4, 8), (4, 3, 7)]
  >>> a,b,c = zip(*together)
  >>> a
(1, 2, 3, 4)
  >>> b
(2, 1, 4, 3)
  >>> c
(6, 5, 8, 7)

But I would consider just keeping the list of 4-tuples as your primary data structure instead of 
keeping four parallel lists.

Kent



More information about the Tutor mailing list