Python: Difference between filter(function, sequence) and map(function, sequence)

前端 未结 6 578
庸人自扰
庸人自扰 2021-01-30 17:13

I\'m reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never

6条回答
  •  有刺的猬
    2021-01-30 17:44

    Filter--Returns the true value's position


    var_list = [10,20,0,1]
    
    var_b = list(filter(lambda var_a : var_a*2,var_list))
    
    print("Values are",var_b)
    

    Output


    Values are [10, 20, 1]

    Map--Returns the actual result


    var_list = [10,20,0,1]
    
    var_b = list(map(lambda var_a : var_a*2,var_list))
    
    print("Values are",var_b)
    

    Output


    Values are [20, 40, 0, 2]

    Reduce--Take the first 2 items in the list,then calls function, In next function call,the result of previous call will be 1st argument and 3rd item in list will be 2nd argument


    from functools import *
    
    var_list = [10,20,0,1]
    
    var_b = list(map(lambda var_a : var_a*2,var_list))
    
    print("Values of var_b ",var_b)
    
    var_c = reduce(lambda a,b:a*2,var_b)
    
    print("Values of var_c",var_c)
    

    Output


    Values of var_b [20, 40, 0, 2]

    Values of var_c 160

提交回复
热议问题