一、map函数
map(func, *iterables) --> map object
# 对0-50分别求平方,并输出求平方之后的结果列表
res = list(map(lambda x:x**2,range(10)))
输出结果:
二、reduce函数
reduce(function, sequence[, initial]) -> value
# 求和0-49
from functools import reduce
res = reduce(lambda x,y:x+y,range(50))
print(res)
输出结果:
三、filter函数
filter(function or None, iterable) --> filter object
# 过滤0-49能被2整除的数
print(list(filter(lambda x: x % 2 == 0, range(50))))
输出结果:
四、sorted 函数
sorted(list,reverse=False) --> new list
test_l = [1, 2, 4, 7, 80, 6, 3, 4]
print(sorted(test_l))
输出结果:
四、闭包
闭包:引用了外部自由变量的函数,wrapper函数引用了外部变量store,所以wrapper函数称为闭包
import time
def log_time(fun):
store = {}
def wrapper(*args, **kwargs):
store.update({'key1': 'value1'})
print(store)
begin_time = time.time()
res = fun(*args, **kwargs)
cost_time = time.time() - begin_time
print(f'excute func cost: {cost_time}')
return res
return wrapper
@log_time
def add(num1, num2):
time.sleep(1)
return num1 + num2
输出结果: