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

前端 未结 7 2247
谎友^
谎友^ 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:54

    When using this in the key parameter of sorted() or min(), given the choice between say operator.itemgetter(1) and lambda x: x[1], the former is typically significantly faster in both cases:


    Using sorted()

    The compared functions are defined as follows:

    import operator
    
    
    def sort_key_itemgetter(items, key=1):
        return sorted(items, key=operator.itemgetter(key))
    
    
    def sort_key_lambda(items, key=1):
        return sorted(items, key=lambda x: x[key])
    

    Result: sort_key_itemgetter() is faster by ~10% to ~15%.

    (Full analysis here)


    Using min()

    The compared functions are defined as follows:

    import operator
    
    
    def min_key_itemgetter(items, key=1):
        return min(items, key=operator.itemgetter(key))
    
    
    def min_key_lambda(items, key=1):
        return min(items, key=lambda x: x[key])
    

    Result: min_key_itemgetter() is faster by ~20% to ~60%.

    (Full analysis here)

提交回复
热议问题