zoukankan      html  css  js  c++  java
  • 高阶函数举例

    求平方根之和:

    import math
    def add(x, y, f):
        return f(x) + f(y)
    print (add(25, 9, math.sqrt))

    更正大小写:

    def f(s):
        return s.title()
    print (list(map(f,['ASdfg','xdSWe','LKxwQ','xcdaFd','ongyTT','AAsdE'])))

    list 内部每个元素平方,返回:

    1 def f(x):
    2     return x*x
    3 print (list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])))

    每一位增加:

    1 def add100(x):
    2     return x+100
    3 hh = [11,22,33]
    4 print(list(map(add100,hh)))

    分别组合:

    1 def f1(x,y):
    2     return (x,y)
    3 l1 = [0,1,2,3,4,5]
    4 l2 = ['a','b','c']
    5 l3 = map(f1,l1,l2)
    6 print(list(l3))

    连续乘机:

    from functools import reduce
    def prod(x,y):
        return  x*y
    print(reduce(prod,[2,4,5,6]))

    100以内可开平方:

    import math
    def is_sqr(x):
        r = int(math.sqrt(x))
        return r*r == x
    print (list(filter(is_sqr, range(1, 102))))

    结果:

    8.0
    ['Asdfg', 'Xdswe', 'Lkxwq', 'Xcdafd', 'Ongytt', 'Aasde']
    [1, 4, 9, 16, 25, 36, 49, 64, 81]
    [111, 122, 133]
    [(0, 'a'), (1, 'b'), (2, 'c')]
    240
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    公众号请关注:侠之大者
  • 相关阅读:
    20165312 我期望的师生关系
    zookeeper04---ZAB协议
    zookeeper03-集群搭建
    zookeeper02
    Zookeeper01
    防止重复提交
    手动抛出异常事务回滚问题
    redis-07主从复制
    redis06-事务
    Redis-05持久化
  • 原文地址:https://www.cnblogs.com/kamil/p/5231888.html
Copyright © 2011-2022 走看看