函数可以当成变量来使用
>>> print
<built-in function print>
>>> type(print)
<class 'builtin_function_or_method'>
>>> print = 10
>>> print
10
>>> type(print)
<class 'int'>
#也可以将一个函数赋值给变量
>>> other = print
>>> other('111')
111
#把函数当一个变量传递
>>> def foo(x,f):
f(x)
>>> foo(10, print)
10
map方法
对可迭代对象中的每一个元素应用function方法, 并返回迭代对象
如果给了多个可迭代参数,则给定的函数必须采用多参数的写法, 或者函数的参数正好匹配
map会通过传递进去的函数..对后面的每一个值进行调用
>>> itera = map(print, [1,2,3,4])
>>> type(itera)
<class 'map'>
>>> itera
<map object at 0x04145B50>
>>> list(itera)
1
2
3
4
[None, None, None, None]
'''list的每一个元素都调用了print, 所以打印了 1-4
... 然后, print的返回值是None, 所以有4个None形成了一个list'''
>>> def foo(x):
return x**2
>>>
>>> print(list(map(foo, list(range(10)))))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> def add(x,y):#map多参数
return x+y
>>> list(map(add, list(range(10))))
>>> list(map(add, [1,2],[3,4]))#返回1+3,2+4
[4, 6]
reduce
该方法需要从 functools 中导入
将两个参数的函数,累计到序列项中
from functools import reduce
>>> def foo(x,y):
return x+y
>>> reduce(foo, list(range(1,11)))#1+2+...+10
55
map和reduce的小应用
从字符串转整数
>>> def str2num(str):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9}[str]
>>> def list2num(x, y):
return x*10+y
>>> reduce(list2num, map(str2num,'12345612847'))
12345612847
filter
过滤器
返回一个迭代器
这个迭代器会返回指定方法为True时的元素
如果函数为None, 则默认什么元素都不返回
>>> def isodd(x):
return x % 2 == 1
>>> reduce(list2num, sorted(filter(isodd, map(str2num, '33312354652224676'))))
13333557
惰性函数
生成器就是其中一种
>>> def sum(*args):
n_sum = 0
for num in args:
n_sum += num
return n_sum
>>> num = sum(1,2,3,4,5)
>>> print(num)
15
>>> def lazysum(*args):
def sum():
n_sum = 0
for num in args:
n_sum += num
return n_sum
return sum
>>> num = lazysum(1,2,3,4,5)#当调用lazysum时会返回一个函数对象,可以在我们需要的时候调用该函数对象得到结果
>>> print(num)
<function lazysum.<locals>.sum at 0x05738E40>
>>> print(num())
15
lambda表达式
匿名函数
>>> foo = lambda num:num*num
>>> foo(210)
44100
>>>
函数绑定
>>> int('0xFF', base=16)
255
>>> int('FF', base=16)
255
>>> int('11', 2) # 2进制转10进制
3
>>> bin2dec = functools.partial(int, base=2)
>>> bin2dec('1010110010101')
5525
>>> bin2dec('11111111')
255
>>> hex2dec = functools.partial(int, base=16)
>>> hex2dec('FF')
255
>>> hex2dec('abcd')
43981
>>>