List comprehension vs. lambda + filter

前端 未结 14 2129
挽巷
挽巷 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 02:49

    I thought I'd just add that in python 3, filter() is actually an iterator object, so you'd have to pass your filter method call to list() in order to build the filtered list. So in python 2:

    lst_a = range(25) #arbitrary list
    lst_b = [num for num in lst_a if num % 2 == 0]
    lst_c = filter(lambda num: num % 2 == 0, lst_a)
    

    lists b and c have the same values, and were completed in about the same time as filter() was equivalent [x for x in y if z]. However, in 3, this same code would leave list c containing a filter object, not a filtered list. To produce the same values in 3:

    lst_a = range(25) #arbitrary list
    lst_b = [num for num in lst_a if num % 2 == 0]
    lst_c = list(filter(lambda num: num %2 == 0, lst_a))
    

    The problem is that list() takes an iterable as it's argument, and creates a new list from that argument. The result is that using filter in this way in python 3 takes up to twice as long as the [x for x in y if z] method because you have to iterate over the output from filter() as well as the original list.

提交回复
热议问题