Lambda

add_one = lambda x:x+1       # 1δΈͺε‚ζ•°οΌŒζ‰§θ‘Œζ“δ½œδΈΊ+1
add_nums = lambda x,y:x+y    # 2δΈͺε‚ζ•°οΌŒζ‰§θ‘Œζ“δ½œδΈΊη›ΈεŠ 

add_one(2)  # 3
add_nums(3,4) # 7

============================================================

from functools import reduce          
numbers = [1,2,3,4]
result_multiply = reduce((lambda x, y: x * y), numbers)
result_add = reduce((lambda x,y: x+y), numbers)

result_multiply  # 24
result_add  # 10

from operator import mul
numbers = [1,2,3,4]
better_add = sum(numbers)
better_multiply =reduce(mul,numbers)

result_add,result_multiply   # 10,24

==========================================================

numbers = [0, 1, 2, -3, 5, -8, 13]
# 提取ε₯‡ζ•°
result = filter(lambda x: x % 2, numbers)
print("Odd Numbers are :",list(result)) # Odd Numbers are : [1, -3, 5, 13]

# 提取偢数
result = filter(lambda x: x % 2 == 0, numbers)
print("Even Numbers are :",list(result)) # Even Numbers are : [0, 2, -8]


#提取正数
result = filter(lambda x: x>0, numbers)
print("Positive Numbers are :",list(result)) # Positive Numbers are : [1, 2, 5,13]

==========================================================
person =[{'name':'Lilei',
          'city':'beijing'},
         {'name':'HanMeiMei',
          'city':'shanghai'}]

names=list(filter(lambda x:x['name']=='Lilei',person)) # ζε–ζŽι›·ηš„δΏ‘ζ―
names  # [{'name': 'Lilei', 'city': 'beijing'}]

===========================================================


numbers = [1,2,3,4,5]
add_one = list(map(lambda n:n+1,numbers))  #map(fun,sequence)
list(add_one)

Last updated