问题
I am needing to sort a list that contains tuples inside. I can sort them using key=lambda
. The list is larger than 1000 elements.
>>> a = [(<object>, 4), (<object>, 5), (<object>, -2)....]
>>> b = sorted(a, key=lambda tup: tup[1])
Is there a faster way to accomplish this?
回答1:
You can use itemgetter
>>> from operator import itemgetter
>>> a = [(None, 4), (None, 5), (None, -2)]
>>> b = sorted(a, key=itemgetter(1))
>>> b
[(None, -2), (None, 4), (None, 5)]
Now if you want to look at the performance, here is itemgetter:
In [3]: %timeit sorted(a, key=itemgetter(1))
1000000 loops, best of 3: 732 ns per loop
In [4]: %timeit sorted(a, key=lambda tup: tup[1])
1000000 loops, best of 3: 804 ns per loop
So, not too dramatic for a small list. Let's upscale this:
In [1]: import random
In [2]: a = [(i, random.randint(0, 100)) for i in range(100000)]
In [3]: %timeit sorted(a, key=itemgetter(1))
10 loops, best of 3: 30.5 ms per loop
In [4]: %timeit sorted(a, key=lambda tup: tup[1])
10 loops, best of 3: 35.6 ms per loop
So still a slightly faster approach even after upscaling. However, I use itemgetter because it's clean code, not because it's faster. Write clean code over performance, and optimize if necessary. 1000 elements is nothing: it's better you know what you're doing.
Just remember, premature [or unnecessary] optimization is the root of all evil. Especially for such a small data set, where it takes milliseconds to complete the entire task.
来源:https://stackoverflow.com/questions/31063359/python-better-alternative-to-sort-key-lambda