您的位置:首页 > 编程语言 > Python开发

python学习——函数式编程——高阶函数

2017-03-29 22:11 513 查看

python学习——函数式编程——高阶函数


函数式编程(高阶函数):1:map && reduce; 2 : filter; 3: sorted;

----------------------------------------------------------------------------------------------------------------------------

函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!
Python对函数式编程提供部分支持。由于Python允许使用变量,因此,Python不是纯函数式编程语言。
函数本身也可以赋值给变量,即:变量可以指向函数。
由于
abs
函数实际上是定义在
import
builtins
模块中的,所以要让修改
abs
变量的指向在其它模块也生效,要用
import
builtins; builtins.abs = 10

把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。
----------------------------------------------------------------------------------------------------------------------------

1:map && reduce

Python内建了
map()
reduce()
函数。
map
函数接收两个参数,一个函数,一个
Iterable
map
将传入的函数依次作用到序列的每个元素,并把结果作为新的
Iterator
返回
reduce
把一个函数作用在一个序列
[x1,x2,x3,...]
上,这个函数必须接收两个参数,
reduce
把结果继续和序列的下一个元素做累积计算

# 1:use map(), inpput:['adam', 'LISA', 'barT']; output:['Adam', 'Lisa', 'Bart'];
def normalize(name):
return (name[0].upper() + name[1:].lower())

list_input = ['adam', 'LISA', 'barT']
list_output = list(map(normalize, list_input))

print('>>1:\ninput:\t', list_input,'\noutput:\t', list_output)

# 2:编写一个prod()函数,可以接受一个list并利用reduce()求积
from functools import reduce

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

def prod(List):
return reduce(multiply, List)

print('>>2:\n3 * 5 * 7 * 9 = ', prod([3, 5, 7, 9]))

# 3:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
def char2num(string):
return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[string]

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

def multifun2(x):
tmp = 1
for x in range(x):
tmp *= 10
return tmp

def str2float(string):
index = 0

for x in range(len(string)):
if ('.' == string[x]):
index = x
break

num1 = reduce(multifun1, map(char2num, string[:index]))
num2 = reduce(multifun1, map(char2num, string[(index + 1):]))

return (num1 + num2/multifun2(len(string) - index - 1))

print(">>3:\nstrfloat('123.45600007') = ", str2float('123.45600007'))
结果:
>>1:
input:	 ['adam', 'LISA', 'barT']
output:	 ['Adam', 'Lisa', 'Bart']
>>2:
3 * 5 * 7 * 9 =  945
>>3:
strfloat('123.45600007') =  123.45600007
>>>

2:filter

Python内建的
filter()
函数用于过滤序列。
filter()
把传入的函数依次作用于每个元素,然后根据返回值是
True
还是
False
决定保留还是丢弃该元素。
filter()
的作用是从一个序列中筛出符合条件的元素。由于
filter()
使用了惰性计算,所以只有在取
filter()
结果的时候,才会真正筛选并每次返回下一个筛出的元素

# 回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()滤掉非回数
def is_palindrome(n):
string = str(n)
for x in (range(len(string)//2)):
if (string[x] != string[-x - 1]):
return False
return True

print(list(filter(is_palindrome, range(1, 200))))
结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]
>>>


3:sorted

sorted()
函数也是一个高阶函数,它还可以接收一个
key
函数来实现自定义的排序
要进行反向排序,不必改动key函数,可以传入第三个参数
reverse=True


# L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 用sorted()按名字/分数排序
def by_name(t):
return t[0]

def by_score(t):
return t[1]

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

print('by_name:\t', sorted(L, key = by_name))
print('by_score:\t', sorted(L, key = by_score, reverse = True))
结果:
by_name:	 [('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
by_score:	 [('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]
>>>

----------------------------------------------------------------------------------------------------------------------------

参考网站:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

----------------------------------------------------------------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息