只是时间:
In [3]: %timeit sorted(sub_list, lambda a,b: cmp(keys.index(a), keys.index(b)))
100000 loops, best of 3: 6.22 us per loop
In [4]: %timeit sublist = [key for key in keys if key in sub_list]
1000000 loops, best of 3: 1.91 us per loop
编辑(更多方法):
%timeit sorted(sub_list, key=keys.index)
100000 loops, best of 3: 2.8 us per loop
此示例使用宏(或它们在中调用的任何内容ipython
),但您可以timeit
通过以下方式使用自己:
import timeit
p = """
keys =['a','c','b','f','e','d','p','t','s','y','h']
sub_list = ['y','b','a','p']"""
s = "sorted(sub_list, lambda a,b: cmp(keys.index(a), keys.index(b)))"
timeit.Timer(stmt=s, setup=p).timeit()
>>> 8.40028386496742
s = "[key for key in keys if key in sub_list]"
timeit.Timer(stmt=s, setup=p).timeit()
>>> 1.9661344551401498
所以你可以尝试所有你能想到的方法并选择最快的