List comprehension vs. lambda + filter

前端 未结 14 2378
挽巷
挽巷 2020-11-22 02:01

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.

My code looked like this:



        
14条回答
  •  没有蜡笔的小新
    2020-11-22 03:01

    It took me some time to get familiarized with the higher order functions filter and map. So i got used to them and i actually liked filter as it was explicit that it filters by keeping whatever is truthy and I've felt cool that I knew some functional programming terms.

    Then I read this passage (Fluent Python Book):

    The map and filter functions are still builtins in Python 3, but since the introduction of list comprehensions and generator ex‐ pressions, they are not as important. A listcomp or a genexp does the job of map and filter combined, but is more readable.

    And now I think, why bother with the concept of filter / map if you can achieve it with already widely spread idioms like list comprehensions. Furthermore maps and filters are kind of functions. In this case I prefer using Anonymous functions lambdas.

    Finally, just for the sake of having it tested, I've timed both methods (map and listComp) and I didn't see any relevant speed difference that would justify making arguments about it.

    from timeit import Timer
    
    timeMap = Timer(lambda: list(map(lambda x: x*x, range(10**7))))
    print(timeMap.timeit(number=100))
    
    timeListComp = Timer(lambda:[(lambda x: x*x) for x in range(10**7)])
    print(timeListComp.timeit(number=100))
    
    #Map:                 166.95695265199174
    #List Comprehension   177.97208347299602
    

提交回复
热议问题