标签:
#函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数 #编写高阶函数,就是让函数的参数能够接收别的函数 def add(x, y, f): return f(x) + f(y) print(add(-1, 1, abs)) def f(x): return x * x r = map(f, [1, 2, 3, 4, 5]) print(list(r)) #map()函数接收两个参数,一个是函数,一个是Iterable, #map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 #reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数, #reduce把结果继续和序列的下一个元素做累积计算 from functools import reduce def add(x, y): return x + y print(reduce(add, [1, 3, 5, 7, 9])) #13579 def fn(x, y): return x * 10 + y print(reduce(fn, [1, 3, 5, 7, 9])) def char2num(s): return {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}[s] print(reduce(fn, map(char2num, ‘13579‘))) #def str2int(s): # def fn(x, y): # return x * 10 + y # def char2num(s): # return {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}[s] # return reduce(fn, map(char2num, s)) #def char2num(s): # return {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}[s] # #def str2int(s): # return reduce(lambda x, y: x * 10 + y, map(char2num, s))
和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素
print(sorted([36, 5, -12, 9, -21])) print(sorted([36, 5, -12, 9, -21], key=abs)) print(sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘])) print(sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower, reverse=True))
def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f = lazy_sum(1, 3, 5, 7, 9) print(f()) def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs f1, f2, f3 = count() print(f1()) print(f2()) print(f3())
#匿名函数 print(list(map(lambda x: x*x, [1, 2, 3]))) #匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果 #def f(x): # return x * x
#def log(func): # @functools.wraps(func) # def wrapper(*args, **kw): # print(‘call %s():‘ % func.__name__) # return func(*args, **kw) # return wrapper import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print(‘%s %s():‘ % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator #@log @log(‘execute‘) def now(): print(‘2015-3-25‘) f = now f() print(now.__name__) print(f.__name__) #把@log放到now()函数的定义处,相当于执行了语句:now = log(now)
print(int(‘12345‘)) print(int(‘12345‘, base=8)) print(int(‘12345‘, 16)) #def int2(x, base=2): # return int(x, base) #print(int2(‘10000000000‘)) #转换二进制 import functools int2 = functools.partial(int, base=2) print(int2(‘100000‘)) print(int2(‘100000‘, base=10)) #创建偏函数时,实际上可以接收函数对象、*args和**kw这3个参数 max2 = functools.partial(max, 10) print(max2(2))
标签:
原文地址:http://www.cnblogs.com/jzm17173/p/4999947.html