# 匿名函数

## 匿名函数

• lambda的主体是一个表达式,而不是一个语句块.
• lambda函数由lambda 参数列表:表达式 构成.
• lambda函数具有返回值,就是实际参数带进去表达式得到的结果.

labmda arg1,arg2:expression

t = lambda : True
t() -> True

def func(): return True
func() - > true

lambda x : x3 求x的三次方
lambda x,y=2:x
y 参数允许拥有默认值

c = lambda x,y,z: x * y * z
c(2,3,4)
24

lambda返回一个元组

a = lambda *z : z
a('abc','def')
('abc','def')

d = lambda **dict:dict
d({"a":2})
{"a":2}

lambda直接后面传参
(lambda x,y:x+y)(100,200)#300

x = (lambda x = 'boo',y='too',z='zoo':x+y+z)
x(abc)

# 'abctoozoo'

L = [lambda x : x2,lambda x:x3,lambda x:x**4]
for f in L;
print(f(2)) # 4,8,16

key = 'B'
dic = {'A':lambda:22,'B':lambda:24,'C':lambda:2*8}
dickey # 8

lower = lambda:x,y:x if x < y else y
lower(2,5) # 2

import sys
showall = lambda x : list(map(sys.stdout.write,x))
showall(['Jerry\n','Sherry\n','Alice\n'])

# Alice

lambda和map联合使用

out = lambda *x : sys.out.write(' '.join(map(str,x)))
out('This','is','a','book!\n')
This is a book!

print(lambda x : x.startswith('b')('Bob')) # false

lambda 和 map,filter联合使用

squares = map(lambda x : x**2,rang(10))
filters = filter(lambda x: x>5 and x < 50,squares)

# [9,16,25,36,49]

lambda和sorted联合使用

# 匿名函数的值返回给key,进行来排序.

death = [('James',32),('Fioman',22),('Yasanlun',35)]
list = sorted(death,key=lambda x : x[1])

# key 制定某种排序规则

nums = range(2,50 + 1)
for i in nums:
nums = filter(lambda x : x ==i or x %i,nums)

a = [1,2,3,4]
b = [5,6,7,8]
sum = map(lambda x,y:x+y,a,b)

# [6,8,10,12]

sentence = "Welcom To Beijing!"
words = sentence.split()
lengths = map(lambda x : len(x),words)