为什么我应该使用operator.itemgetter(x)而不是[x]? [英] Why should I use operator.itemgetter(x) instead of [x]?

查看:72
本文介绍了为什么我应该使用operator.itemgetter(x)而不是[x]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一个更普遍的问题:

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]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆