In [1]:
def square_input(x):
return x**2
square_my = square_input
print square_my(3)
在函数中在定义一个函数
In [2]:
def sum_square(x):
def square_input(x):
return x*x
return sum([square_input(x1) for x1 in x])
print sum_square(range(1,100))
将函数作为一个参数传递
In [3]:
from math import log
def square_input(x):
return x*x
# 定义一个函数,将另一个函数作为参数
def apply_func(func_x,input_x):
return map(func_x,input_x)
a = [2,3,4]
print apply_func(square_input,a)
print apply_func(log,a)
返回一个函数
In [4]:
# 定义一个函数来演示在函数中的返回函数的概念
def cylinder_vol(r):
pi = 3.141
def get_vol(h):
return pi*r**2*h
return get_vol
# 给一个半径
radius = 10
find_volumn = cylinder_vol(radius)
# 给不同的高度值,求解圆柱体的体积
height = 10
print 'volume of cylinder of radius %d and height %d = %.2f cubic unit' % (radius,height,find_volumn(height))
height = 20
print 'volume of cylinder of radius %d and height %d = %.2f cubic unit' % (radius,height,find_volumn(height))
使用装饰器改变函数的行为
In [8]:
from string import punctuation
def pipeline_wrapper(func):
def to_lower(x):
return x.lower()
def remove_punc(x):
for p in punctuation:
x = x.replace(p,'')
return x
def wrapper(*args,**kwargs):
x = to_lower(*args,**kwargs)
x = remove_punc(x)
return func(x)
return wrapper
@pipeline_wrapper
def tokenize_whitespace(inText):
return inText.split()
s = "string. with. Punctuation"
print tokenize_whitespace(s)
In [9]:
# 创建一个简单的列表
a = [10,20,30]
def do_list(a_list,func):
total = 0
for element in a_list:
total += func(element)
return total
# 匿名函数
print do_list(a,lambda x:x**2)
print do_list(a,lambda x:x**3)
b = [lambda x: x%3==0 for x in a]
print b
In [10]:
a = [10,20,30,40,50]
print filter(lambda x:x>20,a)
In [11]:
print zip(range(1,4),range(1,4))
In [12]:
# *操作符用来将集合中的每个元素作为位置参数传递
a = (2,4)
print pow(*a)