Custom Search

Tuesday, April 12, 2011

Python Parallel sorting of lists

Python Parallel sorting of lists

Sometimes you want to sort a list, and there's a second list (of the same length) which should be sorted along with it. Of course, you could have used a single list of 2-tuples in the first place, but sometimes a program requires a different structure. Anyway, it's easy. The following snippet works with two or more lists (the example shows only two).

data = zip(list1, list2)
data.sort()
list1, list2 = map(lambda t: list(t), zip(*data))

Note that zip() returns a list of tuples, so you have to convert the result of the last zip() back to lists. That's what the map() command along with the lambda function does. If you don't actually need lists, the last line could be simplified like this:

tuple1, tuple2 = zip(*data)

No comments:

Post a Comment