为什么我应该使用operator.itemgetter(x)而不是[x]?

编程入门 行业动态 更新时间:2024-10-12 01:25:23
本文介绍了为什么我应该使用operator.itemgetter(x)而不是[x]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这里有一个更普遍的问题:在什么情况下应该在python中使用内置的operator模块?

There is a more general question here: In what situation should the built-in operator module be used in python?

最高答案声称operator.itemgetter(x)比"c2>"更整洁".我觉得事实恰恰相反.

The top answer claims that operator.itemgetter(x) is "neater" than, presumably, than lambda a: a[x]. I feel the opposite is true.

还有其他好处,例如性能吗?

Are there any other benefits, like performance?

推荐答案

除非您的代码处于紧密的内部循环中,并且实际上是性能问题,否则您不必担心性能.而是使用最能表达您意图的代码.有些人喜欢lambda,有些人喜欢itemgetter.有时候,这只是一个品味问题.

You shouldn't worry about performance unless your code is in a tight inner loop, and is actually a performance problem. Instead, use code that best expresses your intent. Some people like lambdas, some like itemgetter. Sometimes it's just a matter of taste.

itemgetter功能更强大,例如,如果您需要一次获取多个元素.例如:

itemgetter is more powerful, for example, if you need to get a number of elements at once. For example:

operator.itemgetter(1,3,5)

与以下相同:

lambda s: (s[1], s[3], s[5])

更多推荐

为什么我应该使用operator.itemgetter(x)而不是[x]?

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

发布评论

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

>www.elefans.com

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