美文网首页
python 基础内容

python 基础内容

作者: 两分与桥 | 来源:发表于2018-03-21 16:12 被阅读12次

    lambda,map, reduce, filter
    lambda 是一个匿名函数表达式

    gg = lambda x, y : x+y
    # add(x, y):
    #      return x + y
    

    python 的三元表达式

    #条件为真时返回的结果  if  条件判断  else  条件为假时返回的结果
    x = 1
    y = 3
    r = x  if x > y else y
    print(r) 
    

    map, 从 list_x 映射到一个新的 list

    list_x = [1, 2, 3, 4, 5, 6, 7, 8]
    
    def square(x):
        return x * x
    
    r = map(square, list_x)
    print(r)
    print(list(r))
    
    #输出结果
    #<map object at 0x000001EAC1360CC0>
    #[1, 4, 9, 16, 25, 36, 49, 64]
    

    lambda 和 map

    list_x = [1, 2, 3, 4, 5, 6, 7, 8]
    
    r = map(lambda x : x*x, list_x)
    print(list(r))
    

    lambda 和 map 传入多个参数迭代

    list_x = [1, 2, 3, 4, 5, 6, 7, 8]
    list_y = [1, 2, 3, 4, 5, 6, 7, 8]
    
    r = map(lambda x, y : x*x + y, list_x, list_y)
    print(list(r))
    #输出结果
    #[2, 6, 12, 20, 30, 42, 56, 72]
    

    传入的 list 没有相同长度

    list_x = [1, 2, 3, 4]
    list_y = [1, 2, 3, 4, 5, 6, 7, 8]
    
    r = map(lambda x, y : x*x + y, list_x, list_y)
    print(list(r))
    #输出结果
    #[2, 6, 12, 20]
    

    reduce

    from functools import reduce
    
    #连续计算,连续调用 lambda
    list_x = ['1', '2', '3', '4', '5', '6', '7', '8']
    r = reduce(lambda x,y : x+y, list_x, "aaa") # 'aaa'
    print(r)
    #输出结果
    #aaa12345678
    

    filter 实现一个筛选函数。依靠返回值的 True or False 来决定保留还是丢弃该元素

    list_x = [1, 0, 1, 0, 1, 1, 0]
    r = filter(lambda x: True if x==1 else False, list_x)
    print(list(r))
    #输出结果
    #[1, 1, 1, 1]
    

    函数式编程,并不适用于python

    相关文章

      网友评论

          本文标题:python 基础内容

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