Python 函数也是一种对象

函数也是一种对象

func = lambda x, y: x+y
print func(3, 4)
def func(x, y):
    return x+y


print func(3, 4)

效果相同。

函数可以作为参数传递

def func(x, y):
    return x+y


print func(3, 4)


def test(f, a, b):
    print 'test'
    print f(a, b)


test(func, 3, 4)
def test(f, a, b):
    print 'test'
    print f(a, b)


test((lambda x, y: x**2 + y), 6, 9)

'''
test
45
'''

map() 函数

re = map((lambda x: x+3), [1, 3, 5, 6])
print re
'''
[4, 6, 8, 9]
'''
re = map((lambda x, y: x+y), [1, 3, 5, 6], [2, 3, 4, 5])
print re
'''
[3, 6, 9, 11]
'''

filter() 过滤出争取的数据

def func(a):
    if a > 100:
        return True
    else:
        return False


print filter(func, [10, 56, 101, 500])
'''
[101, 500]
'''

reduce()函数

reduce函数的第一reduce函数的第一个参数也是函数,但有一个要求,就是这个函数自身能接收两个参数。reduce可以累进地将函数作用于各个参数。如下例:

print reduce((lambda x, y: x+y), [1, 2, 5, 7, 9])

上面例子,相当于(((1+2)+5)+7)+9

猜你喜欢

转载自www.cnblogs.com/jiqing9006/p/10604811.html
今日推荐