匿名函数

def func(a, b):
    return a + b

ret = func(1, 3)

print(ret)

# 匿名函数统一的名字是:<lambda>
fn = lambda a, b : a + b # 定义一个很简单的函数. 复杂的函数不要用lambda
ret = fn(3, 5)
print(ret)
print(func)
print(fn)

使用场景: 配合着sorted, map, filter 一起使用

sorted 排序函数.  让你自己去定义排序的规则

lst = [11,5,36,1,27,58]

s = sorted(lst) # 默认从小到大排序.
print(s)

lst = ["胡一菲", "张伟", "关谷神奇", "曾小贤吕小布", "诺澜"]
# 按照字符串长度排序
def func(s):
    return len(s) # 返回长度

# 执行流程:
# 把可迭代对象中的每一项拿出来, 作为参数传递给后面key函数.
# 函数返回数字. 根据数字进行排序
s = sorted(lst, key=func)
print(s)

print(sorted(lst, key=lambda s:len(s) ))


lst = [
    {"name":"alex", "shengao":150, "tizhong":250},
    {"name":"wusir", "shengao":158, "tizhong":150},
    {"name":"taibai", "shengao":177, "tizhong":130},
    {"name":"ritian", "shengao":165, "tizhong":130},
    {"name":"nvshen", "shengao":160, "tizhong":120},
    {"name":"baolang", "shengao":183, "tizhong":190}
]

# 按照体重进行排序
print(sorted(lst, key=lambda dic:dic['tizhong'],  reverse=True))


# filter 过滤
lst = ["张无忌", "张翠山", "范冰冰", "金毛狮王", "李冰冰"]

# 过滤掉姓张的人
# 把可迭代对象打开. 把内部元素一个一个的传递给前面的函数. 由这个函数决定此项是否保留
f = filter(lambda name : not name.startswith("张"), lst)

print("__iter__" in dir(f)) # 可迭代对象
for el in f:
    print(el)


lst = [
    {"name":"alex", "shengao":150, "tizhong":250},
    {"name":"wusir", "shengao":158, "tizhong":150},
    {"name":"taibai", "shengao":177, "tizhong":130},
    {"name":"ritian", "shengao":165, "tizhong":130},
    {"name":"nvshen", "shengao":160, "tizhong":120},
    {"name":"baolang", "shengao":183, "tizhong":190}
]

# 过滤掉体重大于180的人   想要的是 小于180

f = filter(lambda d : d['tizhong'] <= 180, lst)

print(list(f))

map()  映射函数
lst = ["篮球球", "打打台球", "唱歌", "爬慌山", "步"]

m = map(lambda s: "爱好:"+s , lst)

print(list(m))

lst = [1,5,78,12,16] # 计算每个数字的平方
print([i **2 for i in lst])

m = map(lambda i: i ** 2, lst)
print(list(m))


sorted, filter, map
lambda

  

posted @ 2018-12-12 14:58  =-=-  阅读(133)  评论(0编辑  收藏  举报