Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: sort a list and change another one consequently

I have two lists: one contains a set of x points, the other contains y points. Python somehow manages to mix the x points up, or the user could. I'd need to sort them by lowest to highest, and move the y points to follow their x correspondants. They are in two separate lists.. how do I do it?

like image 945
Gabriele Cirulli Avatar asked Apr 28 '10 20:04

Gabriele Cirulli


2 Answers

You could zip the lists and sort the result. Sorting tuples should, by default, sort on the first member.

>>> xs = [3,2,1]
>>> ys = [1,2,3]
>>> points = zip(xs,ys)
>>> points
[(3, 1), (2, 2), (1, 3)]
>>> sorted(points)
[(1, 3), (2, 2), (3, 1)]

And then to unpack them again:

>>> sorted_points = sorted(points)
>>> new_xs = [point[0] for point in sorted_points]
>>> new_ys = [point[1] for point in sorted_points]
>>> new_xs
[1, 2, 3]
>>> new_ys
[3, 2, 1]
like image 200
danben Avatar answered Oct 22 '22 18:10

danben


>>> xs = [5, 2, 1, 4, 6, 3]
>>> ys = [1, 2, 3, 4, 5, 6]
>>> xs, ys = zip(*sorted(zip(xs, ys)))
>>> xs
(1, 2, 3, 4, 5, 6)
>>> ys
(3, 2, 6, 4, 1, 5)
like image 16
Mike Graham Avatar answered Oct 22 '22 20:10

Mike Graham