码迷,mamicode.com
首页 > 编程语言 > 详细

python,函数式编程

时间:2017-11-13 14:03:45      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:log   map   处理   style   输出   return   匿名   整理   作用   

函数式编程:

特点:允许传递的参数是函数,且允许返回一个函数。

由于Python允许使用变量,因此,Python不是纯函数式编程语言,同样的输入可能输出不同,有副作用。纯函数式编程语言没有变量,输入和输出是确定的,无副作用。

1.高阶函数(Higher-order function):

特点:高阶函数可以接受另一个函数作为参数

变量可以指向函数,函数名也是变量, 所以可以作为参数传入函数。

  1.1 内置的函数:

    map(func, *iterables)

        reduce(function, sequence, initial=None)

  # 将迭代器经函数的处理返回一个新的迭代器,是一种映射。
  list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
   # 返回 [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘] 

   #累计计算:把序列[1, 3, 5, 7, 9]变换成整数13579
   from functools import reduce
   def fn(x, y):
       return x * 10 + y
  reduce(fn, [1, 3, 5, 7, 9])
   # 13579  
 
   # map()和reduce()合用:str’13579‘ 转化为int:13579
   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]
   reduce(fn, map(char2num, 13579))
# 整理为一个函数str2int,这些函数因为就一句也可以用匿名函数写 from functools import reduce 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))

 

python,函数式编程

标签:log   map   处理   style   输出   return   匿名   整理   作用   

原文地址:http://www.cnblogs.com/xiexiaoxiao/p/7825566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!