函数作为变量传递


In [1]:
def square_input(x):
    return x**2

square_my = square_input
print square_my(3)


9

在函数中在定义一个函数


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))


328350

将函数作为一个参数传递


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)


[4, 9, 16]
[0.6931471805599453, 1.0986122886681098, 1.3862943611198906]

返回一个函数


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))


volume of cylinder of radius 10 and height 10 = 3141.00 cubic unit
volume of cylinder of radius 10 and height 20 = 6282.00 cubic unit

使用装饰器改变函数的行为


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)


['string', 'with', 'punctuation']

lambda创造匿名函数


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


1400
36000
[<function <lambda> at 0x047507F0>, <function <lambda> at 0x047508F0>, <function <lambda> at 0x047504F0>]

filter过滤函数


In [10]:
a = [10,20,30,40,50]

print filter(lambda x:x>20,a)


[30, 40, 50]

zip函数用来将两个相同长度的集合合并成对


In [11]:
print zip(range(1,4),range(1,4))


[(1, 1), (2, 2), (3, 3)]

In [12]:
# *操作符用来将集合中的每个元素作为位置参数传递
a = (2,4)
print pow(*a)


16

**操作符将字典中的元素变成命名参数进行传递