List comprehension vs. lambda + filter

前端 未结 14 2153
挽巷
挽巷 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:04

    This is a somewhat religious issue in Python. Even though Guido considered removing map, filter and reduce from Python 3, there was enough of a backlash that in the end only reduce was moved from built-ins to functools.reduce.

    Personally I find list comprehensions easier to read. It is more explicit what is happening from the expression [i for i in list if i.attribute == value] as all the behaviour is on the surface not inside the filter function.

    I would not worry too much about the performance difference between the two approaches as it is marginal. I would really only optimise this if it proved to be the bottleneck in your application which is unlikely.

    Also since the BDFL wanted filter gone from the language then surely that automatically makes list comprehensions more Pythonic ;-)

提交回复
热议问题