List comprehension vs. lambda + filter

前端 未结 14 2021
挽巷
挽巷 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

    Since any speed difference is bound to be miniscule, whether to use filters or list comprehensions comes down to a matter of taste. In general I'm inclined to use comprehensions (which seems to agree with most other answers here), but there is one case where I prefer filter.

    A very frequent use case is pulling out the values of some iterable X subject to a predicate P(x):

    [x for x in X if P(x)]
    

    but sometimes you want to apply some function to the values first:

    [f(x) for x in X if P(f(x))]
    


    As a specific example, consider

    primes_cubed = [x*x*x for x in range(1000) if prime(x)]
    

    I think this looks slightly better than using filter. But now consider

    prime_cubes = [x*x*x for x in range(1000) if prime(x*x*x)]
    

    In this case we want to filter against the post-computed value. Besides the issue of computing the cube twice (imagine a more expensive calculation), there is the issue of writing the expression twice, violating the DRY aesthetic. In this case I'd be apt to use

    prime_cubes = filter(prime, [x*x*x for x in range(1000)])
    
    0 讨论(0)
  • 2020-11-22 03:04

    An important difference is that list comprehension will return a list while the filter returns a filter, which you cannot manipulate like a list (ie: call len on it, which does not work with the return of filter).

    My own self-learning brought me to some similar issue.

    That being said, if there is a way to have the resulting list from a filter, a bit like you would do in .NET when you do lst.Where(i => i.something()).ToList(), I am curious to know it.

    EDIT: This is the case for Python 3, not 2 (see discussion in comments).

    0 讨论(0)
提交回复
热议问题