map:接受两个参数(函数,Iterable),map将传入的函数依次作用于Iterable的每个元素,并且返回新的Iterable
def f(x):return x*x
r = map(f,[1,2,3,4]) #此时的r为惰性求值——可用next()和for...in取值
#通过list()返回全部
print(list(r)) #[1, 4, 9, 16]
reduce:接受两个参数(函数,序列),reduce把一个函数作用于序列上,返回的结果继续和序列的下一个元素做累积计算,其效果为:reduce(f,[x,y,z])=>f(f(x,y),z)
from functools import reduce
def add(x,y):return x+y
reduce(add,[1,3,5,7,9]) #25
filter:过滤序列。接受两个参数(函数,序列),filter把函数作用于序列上,根据返回值是否为True,决定是否放弃该元素
def is_odd(x):return x%2==1
list(filter(is_odd,[1,2,3,4,5,6,7,8,9])) #filter惰性求值[1, 3, 5, 7, 9]
sorted:排序,可排序对象包括数字list、字符串list、dict等,可接受三个参数,后两个为可选
# sorted([],key=express,reverse=True) key:对每个元素的处理方法 reverse:是否反向排序
sorted([0,1,-2,-1,6,3,8],key=abs,reverse=True) #[8, 6, 3, -2, 1, -1, 0]
匿名函数 lambda:匿名函数关键字 :前的元素表示匿名函数的参数 匿名函数不用谢return表达式,返回值就是该表达式的值
m = list(map(lambda x: x*x,[1,2,3,4]))
print(m) #[1, 4, 9, 16]from functools import reducedict1 = {'zhangsan': 90, 'lisi': 100, 'wangwu': 89, 'zhaoliu': 92}
result = sorted(dict1.items(), key=lambda x: x[1])
dict1 = dict(result)
print(dict1)# map 映射 [1,4,9,16,25]
map1 = map(lambda x: x + 2, [1, 2, 3, 4, 5])
print(map1)
print(list(map1))names = ['tom', 'jack', 'lily', 'lucy', 'lily']
map2 = map(lambda x: x.capitalize(), names)
print(tuple(map2))# filter() filter(function or None, iterable) --> filter objectnumbers = [2, 4, 7, 9, 0, 12, 45, 78, 23]
filter1 = filter(None, numbers)
print(list(filter1))filter2 = filter(lambda x: x % 2 == 0, numbers)
print(list(filter2))list1 = ['hello', 30, '80', 50, 'hi100', '99', 'yes']filter3 = filter(lambda x: str(x).isdigit(), list1)
print(list(filter3))filter3 = filter(lambda x: isinstance(x, int) or x.isdigit(), list1)
print(list(filter3))students = [('tom', 21), ('lucy', 18), ('jack', 22), ('lily', 19), ('jerry', 24)]
filter4 = filter(lambda x: x[1] > 20, students)
print(list(filter4))# reduce() reduce(function, sequence[, initial]) -> value initial为初值
list2 = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, list2, 1)
print(result)def add(x, y):return x + y
from functools import reduce
print(reduce(add, [1, 2, 3, 4], 1))#
result = reduce(lambda x, y: x * y, range(1, 6))
print(result)map0 = map(lambda x, y: x + y, [1, 2, 3], [2, 2, 2])
print(list(map0))# a ,b,c = map(int,input('请输入').split(' '))def is_odd(x):return x%2==1
list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))
print(filter(is_odd,[1,2,3,4,5,6,7,8,9]))
装饰器:代码运行期间动态增加功能
#在now函数运行前自动打印日志
import functools
def log(func):@functools.wraps(func)def wrpper(*args,**kw):print("call %s()" % func.__name__)return func(*args,**kw)return wrpper
# 调用装饰器
@log
def now():print("hello")now() #call now() hello
偏函数:functools.partial 把函数的某些参数固定住,返回一个新的函数,使调用更简单
import functools
int2 = functools.partial(int,base=2)
print(int2("1000000")) #64偏函数是functools.partial()函数,将原函数当做第一个参数传入,原函数的各个参数依次作为partial()函数后续的参数,除非使用关键字参数。
举个栗子:import functoolsdef index(n1, n2):return n1 + n2num_func = functools.partial(index, 666) # 666传给了第二个参数n2print(num_func(1)) # 结果输出为667