operator.itemgetter 或 lambda

编程入门 行业动态 更新时间:2024-10-11 01:15:49
本文介绍了operator.itemgetter 或 lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很好奇是否有任何迹象表明 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

本文发布于:2023-06-03 09:51:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/471229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:operator   itemgetter   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!