我很好奇是否有任何迹象表明 operator.itemgetter(0) 或 lambda x:x[0] 哪个更好用,特别是在 sorted() 作为 key 关键字参数,因为这是首先想到的用法.是否存在任何已知的性能差异?是否有任何与 PEP 相关的偏好或指导?
I was curious if there was any indication of which of operator.itemgetter(0) or lambda x:x[0] is better to use, specifically in sorted() as the key keyword argument as that's the use that springs to mind first. Are there any known performance differences? Are there any PEP related preferences or guidance on the matter?
推荐答案根据我对 1000 个元组列表的基准测试,使用 itemgetter 几乎是普通 lambda方法.以下是我的代码:
According to my benchmark on a list of 1000 tuples, using itemgetter is almost twice as quick as the plain lambda method. The following is my code:
In [1]: a = list(range(1000)) In [2]: b = list(range(1000)) In [3]: import random In [4]: random.shuffle(a) In [5]: random.shuffle(b) In [6]: c = list(zip(a, b)) In [7]: %timeit c.sort(key=lambda x: x[1]) 81.4 µs ± 433 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [8]: random.shuffle(c) In [9]: from operator import itemgetter In [10]: %timeit c.sort(key=itemgetter(1)) 47 µs ± 202 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)我还针对不同的列表大小测试了这两种方法的性能(以微秒为单位的运行时间).
I have also tested the performance (run time in µs) of this two method for various list size.
+-----------+--------+------------+ | List size | lambda | itemgetter | +-----------+--------+------------+ | 100 | 8.19 | 5.09 | +-----------+--------+------------+ | 1000 | 81.4 | 47 | +-----------+--------+------------+ | 10000 | 855 | 498 | +-----------+--------+------------+ | 100000 | 14600 | 10100 | +-----------+--------+------------+ | 1000000 | 172000 | 131000 | +-----------+--------+------------+(生成上图的代码可以在这里)
(The code producing the above image can be found here)
结合从列表中选择多个元素的简洁性,itemgetter 显然是用于排序方法的赢家.
Combined with the conciseness to select multiple elements from a list, itemgetter is clearly the winner to use in sort method.
更多推荐
operator.itemgetter 或 lambda
发布评论