美文网首页
Python Lambda, map, filter

Python Lambda, map, filter

作者: __小赤佬__ | 来源:发表于2019-04-19 04:48 被阅读0次
    lambda arguments: expression
    
    • This function can have any number of arguments but only one expression, which is evaluated and returned.
    • One is free to use lambda functions wherever function objects are required.
    • You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
    • It has various uses in particular fields of programming besides other types of expressions in functions.
    # Example
    def cube(y): 
        return y*y*y; 
      
    g = lambda x: x*x*x 
    
    print(g(7)) 
    print(cube(5)) 
    

    Using lambda with...

    # filter() with lambda() 
    li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
    final_list = list(filter(lambda x: (x%2 != 0) , li)) 
    print(final_list) 
    
    # map() with lambda()  
    li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
    final_list = list(map(lambda x: x*2 , li)) 
    print(final_list) 
    
    # reduce() with lambda() 
    from functools import reduce
    li = [5, 8, 10, 20, 50, 100] 
    sum = reduce((lambda x, y: x + y), li) 
    print (sum) 
    

    Map

    map(fun, iter)
    
    def addition(n): 
        return n + n 
      
    # We double all numbers using map() 
    numbers = (1, 2, 3, 4) 
    result = map(addition, numbers) 
    print(list(result)) 
    
    # Double all numbers using map and lambda 
    numbers = (1, 2, 3, 4) 
    result = map(lambda x: x + x, numbers) 
    print(list(result)) 
    
    # Add two lists using map and lambda 
    numbers1 = [1, 2, 3] 
    numbers2 = [4, 5, 6] 
    result = map(lambda x, y: x + y, numbers1, numbers2) 
    print(list(result))  # [5, 7, 9]
    
    # List of strings 
    l = ['sat', 'bat', 'cat', 'mat'] 
    
    # map() can listify the list of strings individually 
    test = list(map(list, l)) 
    print(test) 
    # [['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
    

    相关文章

      网友评论

          本文标题:Python Lambda, map, filter

          本文链接:https://www.haomeiwen.com/subject/obrfgqtx.html