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

前端 未结 7 2251
谎友^
谎友^ 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 05:50

    As performance was mentioned, I've compared both methods operator.itemgetter and lambda and for a small list it turns out that operator.itemgetter outperforms lambda by 10%. I personally like the itemgetter method as I mostly use it during sort and it became like a keyword for me.

    import operator
    import timeit
    
    x = [[12, 'tall', 'blue', 1],
    [2, 'short', 'red', 9],
    [4, 'tall', 'blue', 13]]
    
    
    def sortOperator():
        x.sort(key=operator.itemgetter(1, 2))
    
    def sortLambda():
        x.sort(key=lambda x:(x[1], x[2]))
    
    
    if __name__ == "__main__":
        print(timeit.timeit(stmt="sortOperator()", setup="from __main__ import sortOperator", number=10**7))
        print(timeit.timeit(stmt="sortLambda()", setup="from __main__ import sortLambda", number=10**7))    
    
    >>Tuple: 9.79s, Single: 8.835s
    >>Tuple: 11.12s, Single: 9.26s
    

    Run on Python 3.6

提交回复
热议问题