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