这里有一个更普遍的问题:在什么情况下应该在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]?
发布评论