Python 函数式编程学习

描述:通过将函数作为参数,使得功能类似的函数实现可以整合到同一个函数。

Before

 1 def getAdd(lst):
 2     result = 0
 3     for item in lst:
 4         result += item
 5     return result
 6 
 7 def getMul(lst):
 8     result = 1
 9     for item in lst:
10         result *= item
11     return result
12 
13 print getAdd([1,2,3,4])
14 print getMul([1,2,3,4])

After

 1 def getOperator(lst, init_val, func):
 2     result = init_val
 3     for item in lst:
 4         result = func(result, item)
 5     return result
 6 
 7 def add(x, y):
 8     return x + y
 9 
10 def mul(x, y):
11     return x * y
12 
13 print getOperator([1,2,3,4], 0, add)
14 print getOperator([1,2,3,4], 1, mul)

参考地址:

http://www.cnblogs.com/huxi/archive/2011/06/24/2089358.html

posted @ 2014-07-17 16:55  mess4u  阅读(132)  评论(0编辑  收藏  举报