python 之 匿名函數

5.14 匿名函數

lambda x , y : x+y

1 匿名的目的就是要沒有名字,給匿名函數賦給一個名字是沒有意義的 2 匿名函數的參數規則、作用域關係與有名函數是一樣的 3 匿名函數的函數體通常應該是 一個表達式,該表達式必須要有一個返回值

f=lambda x,n:x ** n
print(f(2,3))

lambda匿名函數的應用:**max,min,sorted,map,reduce,filter**

求工資最高的人:max

salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
def get(k):
    return salaries[k]
print(max(salaries,key=get)) #'alex' 
print(max(salaries,key=lambda x:salaries[x]))
info = [
    {'name': 'egon', 'age': '18', 'salary': '3000'},
    {'name': 'wxx', 'age': '28', 'salary': '1000'},
    {'name': 'lxx', 'age': '38', 'salary': '2000'}
]
max(info, key=lambda dic: int(dic['salary']))
max([11, 22, 33, 44, 55])

求工資最低的人:min

salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
print(min(salaries,key=lambda x:salaries[x]))   # 'yuanhao' 
 info=[
            {'name':'egon','age':'18','salary':'3000'},
            {'name':'wxx','age':'28','salary':'1000'},
            {'name':'lxx','age':'38','salary':'2000'}
        ]
min(info,key=lambda dic:int(dic['salary']))

把薪資字典,按照薪資的高低排序sort

salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
alaries=sorted(salaries) # 默認按照字典的鍵排序
print(salaries)
​
# salaries=sorted(salaries,key=lambda x:salaries[x])  #默認是升序排
alaries=sorted(salaries,key=lambda x:salaries[x],reverse=True) #降序
print(salaries)
info=[
            {'name':'egon','age':'18','salary':'3000'},
            {'name':'wxx','age':'28','salary':'1000'},
            {'name':'lxx','age':'38','salary':'2000'}
        ]
l=sorted(info,key=lambda dic:int(dic['salary']))

map 映射, 循環讓每個元素執行函數,將每個函數執行的結果保存到新的列表中

v1 = [11,22,33,44]
result = map(lambda x:x+100,v1) # 第一個參數為執行的函數,第二個參數為可迭代元素.
print(list(result)) # [111,122,133,144]
names=['alex','wupeiqi','yuanhao','egon']
res=map(lambda x:x+'_NB' if x == 'egon' else x + '_SB',names)
print(list(res))

reduce , 對參數序列中元素進行累積.

import functools
v1 = ['wo','hao','e']
​
def func(x,y):
    return x+y
result = functools.reduce(func,v1) 
print(result)   # wohaoe
​
result = functools.reduce(lambda x,y:x+y,v1)
print(result)   # wohaoe
from functools import reduce
l=['my','name','is','alex','alex','is','sb']
res=reduce(lambda x,y:x+' '+y+' ',l)
print(res)
#my name  is  alex  alex  is  sb 

filter , 按條件篩選.

result=filter(lambda x:x > 2,[1,2,3,4])
print(list(result))
v1 = [11,22,33,'asd',44,'xf']
​
# 一般做法
def func(x):
    if type(x) == int:
        return True
    return False
result = filter(func,v1)
print(list(result))     # [11,22,33,44]
# 簡化做法
result = filter(lambda x: True if type(x) == int else False ,v1)
print(list(result))
​
# 極簡做法
result = filter(lambda x: type(x) == int ,v1)
print(list(result))
names=['alex_sb','wxx_sb','yxx_sb','egon']
res=filter(lambda x:True if x.endswith('sb') else False,names)
res=filter(lambda x:x.endswith('sb'),names)
print(list(res))        #['alex_sb', 'wxx_sb', 'yxx_sb']
ages=[18,19,10,23,99,30]
res=filter(lambda n:n >= 30,ages)
print(list(res))        #[99, 30]
salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
res=filter(lambda k:salaries[k] >= 10000,salaries)
print(list(res))            #['alex', 'wupeiqi']
点赞

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *