Python中函数可以作为参数传入另一个函数中
map和reduce
Python3和Python2中略有不同
- Python3中map()返回的是map对象,可以用list()转化为列表
- Python3中的reduce需要从functools中导入
Python3中:
>>> def f(x):
... return x+1
>>> map(f,[1,2,3,4])
<map object at 0x10836df60>
>>> list(map(f,[1,2,3,4]))
[2, 3, 4, 5]
>>> a=map(str,[1,2,3])
>>> a.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'map' object has no attribute 'next'
>>> next(a)
'1'
>>> def add(x,y):
... return x+y
>>> reduce(add,[1,2,3,4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'reduce' is not defined
>>> from functools import reduce
>>> reduce(add,[1,2,3,4])
10
Python2中:
>>> def f(x):
... return x+1
...
>>> map(f,[1,2,3,4])
[2, 3, 4, 5]
>>> reduce(lambda x,y:x+y,[1,2,3])
6
filter
filter和map情况类似
# Python2
>>> def is_odd(n):
... return n%2==1
...
>>> filter(is_odd,[1,2,3,4])
[1, 3]
>>> exit()
# Python3
>>> def is_odd(n):
... return n%2==1
...
>>> filter(is_odd,[1,2,3,4])
<filter object at 0x10df5ff98>
>>> list(filter(is_odd,[1,2,3,4]))
[1, 3]
>>>
sorted
2,3中表现一致
>>> sorted([{'name':'a','views':13},{'name':'b','views':15},{'name':'c','views':1}],key=lambda x:x['views'],reverse=True)
[{'name': 'b', 'views': 15}, {'name': 'a', 'views': 13}, {'name': 'c', 'views': 1}]
装饰器
import functools
# 对应 @log,无参数
def log(func):
def wrapper(*args, **kwargs):
print('log....')
return func(*args, **kwargs)
return wrapper
# 对应@log_arg('xxx'),带参数
def log_arg(arg):
def wrapper1(func):
# 这个的作用是使func.__name__不变
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(arg)
print('log...')
return func(*args, **kwargs)
return wrapper
return wrapper1
# 对应@log_all 和@log_all('xxx'),参数可选
def log_all(arg):
def wrapper1(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(arg)
print('log...')
return func(*args, **kwargs)
return wrapper
@functools.wraps(arg)
def wrapper(*args, **kwargs):
print('log...')
return arg(*args, **kwargs)
if callable(arg):
return wrapper
else:
return wrapper1
@log_all
def tt(i):
print('ok')
print(i)
tt(11)
#log(tt)(*args, **kwargs)
print('tt->name', tt.__name__)
@log_all('abc')
def kk(i):
print('kk')
print(i)
kk(22)
print('kk->name', kk.__name__)
#log_arg('abc')(kk)(*args, **kwargs)
functools.partial
固定函数的一部分参数,生成新的函数
>>> import functools
>>> int2=functools.partial(int,base=2)
>>> int('12',base=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '12'
>>> int2
<functools.partial object at 0x10e5b5e10>
>>> int2('10010')
18
>>> max10=functools.partial(max,10)
>>> max10(1,2)
10
>>> max10(10,11)
11