高阶函数举例

求平方根之和:

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]

 

posted @ 2016-03-01 17:36  侠之大者kamil  阅读(291)  评论(0编辑  收藏  举报