I have two lists, x and y, and I want to sort x and permute y by the permutation of x-sorting. For example, given
x = [4, 2, 1, 3]
y = [40, 200, 1, 30]
I want to get
x_sorted = [1,2,3,4]
y_sorted = [1, 200, 30, 40]
As discussed in past questions, a simple way to solve this is
x_sorted, y_sorted = zip(*sorted(zip(x,y)))
Here is my question: What is the FASTEST way to do this?
I have three methods to do the task.
import numpy as np
x = np.random.random(1000)
y = np.random.random(1000)
method 1:
x_sorted, y_sorted = zip(*sorted(zip(x,y))) #1.08 ms
method 2:
foo = zip(x,y)
foo.sort()
zip(*foo) #1.05 ms
method 3;
ind = range(1000)
ind.sort(key=lambda i:x[i])
x_sorted = [x[i] for i in ind]
y_sorted = [y[i] for i in ind] #934us
Is there a better method, which executes faster than above three methods?
Additional questions.
- Why method 2 is not faster than method 1 though it uses sort method?
- If I execute method 2 separately, it is faster. In IPython terminal,
I have
%timeit foo = zip(x,y) #1000 loops, best of 3: 220 us per loop
%timeit foo.sort() #10000 loops, best of 3: 78.9 us per loop
%timeit zip(*foo) #10000 loops, best of 3: 73.8 us per loop