定义:一个函数接收另一个函数作为参数,这种函数称为高阶函数
变量指向函数:函数本身赋值给变量。
>>> abs(10) #函数调用 10 >>> abs #函数本身 <built-in function abs> >>> a = abs(10) >>> a 10 >>> b = abs >>> b <built-in function abs> >>> b(10) 10 >>>
函数名也是变量:函数名其实就是指向函数的变量。如abs()中abs为变量,它指向一个可以计算绝对值的函数。
>>> abs = 10 #abs这个变量指向了一个整数10 >>> abs(10) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> abs(10) TypeError: 'int' object is not callable >>> abs 10 >>> del abs #可以恢复abs的使用
传入函数:高阶函数,让函数的参数能够接收别的函数
>>> def add(x,y,f): return f(x) + f(y) >>> add(-5,6,abs) 11 >>>
>>> from math import sqrt >>> def some(x,*fs): s = [f(x) for f in fs] return s >>> print(some(2,sqrt,abs,bin,hex,oct)) [1.4142135623730951, 2, '0b10', '0x2', '0o2'] >>>
map():接收两个参数,一个函数,一个Iterable,map将传入的参数依次作用到序列的每个元素,并把结果作为新的Iterable返回
def f(x):
return x*x
>>> r = map(f,[1,2,3,4,5,6,7,8,9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> r
<map object at 0x02CB0BD0>
>>>
map()函数与for循环的区别:
>>> for n in [1,2,3,4,5,6,7,8,9]:
L.append(f(n))
>>> print(L)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
>>> list(map(str,[1,2,3,4,5,6]))
['1', '2', '3', '4', '5', '6']
reduce():reduce(f,[x1,x2,x3,x4]) = f(f(f(x1,x2),x3),x4)
>>> from functools import reduce
>>> def add(x,y):
return x + y
>>> reduce(add,[1,3,5,7,9])
25
>>> def fn(x,y):
return x*10 + y
>>> reduce(fn,[1,3,5,7,9])
13579
>>>
结合使用map()和reduce():
>>> from functools import reduce
>>> 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]
>>> reduce(fn,map(char2num,'13579'))
13579
>>> map(char2num,'13579')
<map object at 0x02CB0BF0>
>>> list(map(char2num,'13579'))
[1, 3, 5, 7, 9]
将字符串转换为数字:
from functools import reduce 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] def str2int(s): return reduce(lambda x, y: x*10 + y, map(char2num,s)) >>> str2int('1024') 1024 >>>
使用map函数实现给定列表中字符串首字母大写。
from string import capwords L1 = ['zyj','sl','SB'] L2 = list(map(capwords,L1)) print(L2) def normalize(name): return name.title() name = ['zyj','wh','SBj'] L = list(map(normalize,name)) print(L) >>> ['Zyj', 'Sl', 'Sb'] ['Zyj', 'Wh', 'Sbj'] >>>
from functools import reduce def prod(L): return reduce(lambda x,y: x*y, L) L1= [1,3,5,7,9] print(prod(L1)) >>> 945 >>>
将小数转换为浮点数:
from functools import reduce 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] def str2folat(s): return reduce(lambda x,y: x*10+y, map(char2num,s)) s= '123.456' i = s.find('.') n = len(s)-(i+1) s1 = s[:i]+s[(i+1):] #s1,s2 = s.split('.') #s1 = s1+s2 result = str2folat(s1)/10**n print(result) >>> 123.456 >>>