我有两个列表,x 和 y,我想通过 x 排序的排列对 x 和 y 进行排序。例如,给定
x = [4, 2, 1, 3]
y = [40, 200, 1, 30]
我想得到
x_sorted = [1,2,3,4]
y_sorted = [1, 200, 30, 40]
正如在过去的问题中所讨论的,解决这个问题的一个简单方法是
x_sorted, y_sorted = zip(*sorted(zip(x,y)))
这是我的问题:最快的方法是什么?
我有三种方法来完成这项任务。
import numpy as np
x = np.random.random(1000)
y = np.random.random(1000)
方法一:
x_sorted, y_sorted = zip(*sorted(zip(x,y))) #1.08 ms
方法二:
foo = zip(x,y)
foo.sort()
zip(*foo) #1.05 ms
方法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
有没有比上述三种方法执行速度更快的更好方法?
附加问题。
- 为什么方法 2 虽然使用排序方法但并不比方法 1 快?
- 如果我单独执行方法2,它会更快。在 IPython 终端中,
我有
%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