2021-03-24 python数据处理系统学习(五)高级函数
1、匿名函数
比较简单的函数可以直接用匿名函数
g=lambda x:x**2
g(3)
Out[33]: 9
f=lambda x: 'A' if x==1 else 'B'
print(f(1))
print(f(2))
A
B
g=lambda x,y,z: x*1+y*2+z*3
g(1,2,3)
Out[35]: 14
2、Map函数
对序列中的每个元素都作用一遍
items=[1,2,3,4,5,6]
def f(x):
return x**2
list(map(f,items))
Out[37]: [1, 4, 9, 16, 25, 36]
3、reduce函数
from functools import reduce
def f(x,y):
return x+y
item=[1,2,3,4,5,6,7,8,9,10]
result=reduce(f,item)#本质上是累计求和的过程
result
Out[39]: 55
def add_str(x,y):
return x+y
items=['this','is','China','!']
result=reduce(add_str,items)
result
Out[42]: 'thisisChina!'
4、filter函数
过滤出偶数
list(filter (lambda x:x%2==0,range(21)))
Out[43]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
过滤出整数
items=[1,2,3,4,'one',123.34,'1234']
list(filter(lambda x:1 if isinstance((x), int)else 0,items))
Out[44]: [1, 2, 3, 4]