Python——Python高阶函数(十)
1. lambda表达式(匿名函数)
# coding=utf-8
# lambda表达式(匿名函数)
# 计算圆形的面积
# pi * r * r
# 导入数学模块
import math
def circle_area(r):
result = math.pi * r * r
return result
r = circle_area(3)
print (r)
"""
lambda是一个关键字
冒号前边的r是这个函数的参数
冒号后边的是这个函数的运算逻辑
"""
result = lambda r:math.pi * r * r
r = result(3)
print (r)
def calc_function(o):
if o == "+":
return lambda a,b : a + b
elif o == "-":
return lambda a,b : a - b
elif o == "*":
return lambda a,b : a * b
elif o == "/":
return lambda a,b : a / b
f = calc_function("*")
print (f)
r = f(3,4)
print (r)
print打印结果:
28.2743338823
28.2743338823
<function <lambda> at 0x03159B70>
12
2. map自动拆分的计算函数
# coding=utf-8
# map函数
my_list = [1,2,3,4,5]
# 1
result = []
for i in my_list:
result.append(i + 1)
print (result)
# 2
def add_one(e):
return e + 1
r = map(add_one,my_list)
print (list(r))
def add_two(e):
if e == 1:
return e + 3
elif e == 2:
return 2 - 1
else:
return e
r =map(add_two,my_list)
print (list(r))
# 3
print (list(map(lambda e:e+1,my_list)))
print打印结果:
[2, 3, 4, 5, 6]
[2, 3, 4, 5, 6]
[4, 1, 3, 4, 5]
[2, 3, 4, 5, 6]
3. reduce自动堆叠计算函数
# coding=utf-8
# reduce
# 导入reduce
from functools import reduce
a =[2,4,6,8,10]
def add(x,y):
return x + y
result = reduce(add,a)
print (result)
print (reduce(lambda x,y : x+y,a))
print打印结果:
30
30
4. filter过滤器函数
# coding=utf-8
# filter函数
letter=['a',"B",'c',"D",'e',"F"]
upper_letter = filter(lambda x: x == x.upper(),letter)
print (upper_letter)
print (list(upper_letter))
student_name = ['李元芳','李建国','莫怀羽']
print (list(filter(lambda x:x.startwith("李"),
student_name)))
print打印结果:
['B', 'D', 'F']
['B', 'D', 'F']
['李元芳','李建国']