Python入门 函数式编程

高阶函数

map/reduce

from functools import reduce

def fn(x, y):
	return x * 10 + y

def char2num(s):
	digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}
	return digits[s]

print(list(map(char2num, "12357")))

print(reduce(fn, map(char2num, "12357")))

编写成一个函数

from functools import reduce

digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}

def str2int(s):
	def fn(x,y):
		return x*10+y
	def str2num(s):
		return digits[s]
	return reduce(fn, map(str2num, s))

print(str2int("987654321"))

lambda表达式改写

from functools import reduce

digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}

def str2num(s):
	return digits[s]	

def str2int(s):
	return reduce(lambda x,y:x*10+y, map(str2num, s))

print(str2int("23718912739"))

filter 过滤

def odd(n):
	return n % 2 == 1;

print(list(filter(odd, range(10))))

sorted 排序

实现降序排列

def cmp(x):
	return -x;
print(sorted(l, key=cmp))

返回函数

def createCounter():
	L = [0]
	def counter():
		L[0] += 1
		return L[0]
	return counter

counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
    print('测试通过!')
else:
    print('测试失败!')

参考文章

python高阶函数

posted @ 2019-04-07 22:02  Draymonder  阅读(290)  评论(0编辑  收藏  举报