Python 数据科学指南1.11-1.14 函数操作

Python支持函数式编程,除了命令范式。它们拥有属性,可以被引用,并且可以被分配给一个变量。

1.将函数作为变量传递

示例代码1:

#1.定义一个简单的函数
def square_input(x):
	return x*x

#2.把它分配给一个变量
square_me = square_input

#3.最后调用这个变量
print (square_me(5))

上述示例演示了,在Python里,我们可以将函数作为一个变量来对待,这是函数式编程的重要概念。

2.在函数中嵌入函数:在一个函数中定义另外一个函数

示例代码2:

#1. 定义一个函数,返回给定输入数值的平方和
def sum_square(x):
	def square_input(x):
		return x*x
	return sum([square_input(x1) for x1 in x])



#2.输出结果来检查是否正确
print (sum_square([2,4,5]))

3.将函数作为参数传递:讲一个函数作为另一个函数的参数传递

示例代码3:

from math import log

def square_input(x):
	return x*x

#1.定义一个类函数,它将另外一个函数作为输入
#并将它应用到给定的输入序列上。
#func_x是一个接受函数的参数,input_x接受序列;
#采用map将给定的函数应用到序列的所有元素。map返回值是<map object at 0x10fc74390>,需要使用list(map())将其转换后输出。
def apply_func(func_x,input_x):
	return list(map(func_x,input_x))

#2.这里使用apply_func()函数,并效验结果
a=[2,3,4]

print (apply_func(square_input,a))
print (apply_func(log,a))

输出结果:

[4, 9, 16]

[0.6931471805599453, 1.0986122886681098, 1.3862943611198906]

4.返回一个函数:在一个函数里返回另一个函数

示例代码:给定半径,求出不同高度的圆柱体的体积。

Volume = area*height =pi*r^2*h

#1. 定义一个函数来演示在函数中返回函数的概念
#外部函数 r是参数,内部函数 h是参数。对于给定的半径r,也即cylinder_vol()的参数,不同的高度值被作为参数传递给了get_vol()
def cylinder_vol(r):
	pi = 3.141
	def get_vol(h):
		return pi*r**2*h
	return get_vol

#2.定义一个固定的半径值,在此给定半径和任意高度条件下,写一个函数来求出体积
radius = 10
#调用cylinder_vol函数,返回get_vol函数,存在find_volume变量中。
find_volume = cylinder_vol(radius)

#3.给出不同的高度,求解圆柱体的体积
height = 10
print ("Volume of cylinder of radius %d and height %d = %.2f cubic units"%(radius,height,find_volume(height)))
height = 20
print ("Volume of cylinder of radius %d and height %d = %.2f cubic units"%(radius,height,find_volume(height)))


Volume of cylinder of radius 10 and height 10 = 3141.00 cubic units

Volume of cylinder of radius 10 and height 20 = 6282.00 cubic units

猜你喜欢

转载自blog.csdn.net/cjx_cqupt/article/details/88237279