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

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

    Leaving aside performance and code style, itemgetter is picklable, while lambda is not. This is important if the function needs to be saved, or passed between processes (typically as part of a larger object). In the following example, replacing itemgetter with lambda will result in a PicklingError.

    from operator import itemgetter
    
    def sort_by_key(sequence, key):
        return sorted(sequence, key=key)
    
    if __name__ == "__main__":
        from multiprocessing import Pool
    
        items = [([(1,2),(4,1)], itemgetter(1)),
                 ([(5,3),(2,7)], itemgetter(0))]
    
        with Pool(5) as p:
            result = p.starmap(sort_by_key, items)
        print(result)
    

提交回复
热议问题