Python之匿名函数使用示例

#!/usr/bin/env python
# -*- coding:utf8 -*-

# #匿名函数
# y = lambda x:x+1
# print(y(10))

name = 'AK'
#一般函数形式
def change_name(x):
    return name+'_M4'
res = change_name(name)
print(res)
#匿名函数形式
res = lambda x:name+'_M4'
print(res(name))

#用处:
#通常是与其他函数联合使用的,不应该独立存在
#示例中只为了演示其单独存在时是怎样运行的,其本质不是怎样使用num = [1,2,10,5,3,7]

def add_one(x):
    return x + 1

def reduce_one(x):
    return x - 1

def pf(x):
    return x**2

def map_test(f,array):
    tmp = []
    for i in array:
        res = f(i)
        tmp.append(res)
    return tmp
print('使用经典函数')
print(map_test(add_one,num))
print(map_test(reduce_one,num))
print(map_test(pf,num))
print('使用lambda')
print(map_test(lambda x:x+1,num))
print(map_test(lambda x:x-1,num))
print(map_test(lambda x:x**2,num))

msg = 'iuasghduADS'
print(list(map(lambda x:x.upper(),msg)))

猜你喜欢

转载自www.cnblogs.com/lzn-2018/p/10757646.html
今日推荐