Why should I use operator.itemgetter(x) instead of [x]?

前端 未结 7 2241
谎友^
谎友^ 2020-12-01 05:14

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

The top answer claims that operator.itemgetter(

相关标签:
7条回答
  • 2020-12-01 06:02

    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 is more powerful, for example, if you need to get a number of elements at once. For example:

    operator.itemgetter(1,3,5)
    

    is the same as:

    lambda s: (s[1], s[3], s[5])
    
    0 讨论(0)
提交回复
热议问题