python函数式编程

一、python-Map()函数

1、首先学习python中的字符串大小写转换:

s = 'hEllo pYthon'

python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.upper()  全部转换为大写

python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.lower()  全部转换为小写

python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.capitalize()  首字母大写,其余的小写

python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.title()  所有单词首字母大写,其余小写

2、Map()函数:

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

练习:除首字母大写,其余小写

输入:['adam', 'LISA', 'barT']
      输出:['Adam', 'Lisa', 'Bart']

答案:

def format_name(s):
      return s.title()

print map(format_name, ['adam', 'LISA', 'barT'])

二、 reduce函数:reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

练习:

Python内置了求和函数sum(),但没有求积的函数,请利用recude()来求积:

输入:[2, 4, 5, 7, 12]
输出:2*4*5*7*12的结果

def prod(x, y):
    return x*y

print reduce(prod, [2, 4, 5, 7, 12])

三、python中filter()函数

filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

练习:

请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

答案:

import math

def is_sqr(x):
return math.sqrt(x) % 1 == 0

print filter(is_sqr, range(1, 101))

四、python中返回函数

1、匿名函数

1)、计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:

list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
2)、使用匿名函数,可以不必定义函数名,直接创建一个函数对象,很多时候可以简化代码:
例:def is_not_empty(s):
    return s and len(s.strip()) > 0
filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])
简化为:
print filter(lambda s:s and len(s.strip()) > 0, ['test', None, '', 'str', '  ', 'END']
#strip(): 方法用于移除字符串头尾指定的字符(默认为空格)。

2、返回函数:Python的函数不但可以返回int、str、list、dict等数据类型,还可以返回函数!
例:
请编写一个函数calc_prod(lst),它接收一个list,返回一个函数,返回函数可以计算参数的乘积。

def calc_prod(lst):
def prod():
reduce(lambda x, y : x * y, lst)
return prod

f = calc_prod([1, 2, 3, 4])
print f()

原文地址:https://www.cnblogs.com/liuqingqing/p/6759566.html