Python基礎(chǔ)(3)- lambda表達(dá)式

這里簡單整理下,lambda表達(dá)式相關(guān)內(nèi)容。

什么是lambda表達(dá)式

lambda表達(dá)式,是一個匿名函數(shù),用起來方便快捷一些

#lambda 參數(shù):操作(參數(shù))

fun_add = lambda x: x+1

print(fun_add(1))
print(fun_add(10))

這里,一個簡單的加1的函數(shù),看起來也很直觀

fun_add = lambda x,y: x+y

print(fun_add(3,4))
print(fun_add(8,9))

這是x+y的函數(shù),的確簡潔很多
看網(wǎng)上,提到lambda表達(dá)式的話,都會提到函數(shù)式編程,一些常用的函數(shù),像map,reduce,filter,sorted,

map函數(shù)

map是Python內(nèi)置的一個函數(shù),接收2個參數(shù),一個函數(shù),一個或多個可迭代參數(shù)

map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables.  Stops when the shortest iterable is exhausted.
d1 = [1,2,3,4,5]

def add(x):
    return x+10

t = map(add , d1)
print('原來的list:',d1)
print('執(zhí)行add后的list:',list(t))

我們定義了一個函數(shù),對傳入的參數(shù)加10,一個list


map把這個函數(shù),作用在每一個list的元素上,
這里呢,我們就可以用lambda表達(dá)式寫,方便又直觀

d1 = [1,2,3,4,5]
t = map(lambda x: x+10 , d1)
print('原來的list:',d1)
print('執(zhí)行add后的list:',list(t))

我們也可以傳2個list,這里會計(jì)算2個list的和

s1 = [1,2,3]
s2 = [4,5,6]
t = map(lambda x,y: x+y,s1,s2)
print(list(t)) ##[5, 7, 9]

reduce函數(shù)

reduce會將function作用于sequence,function接收2個參數(shù)

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
t = reduce(lambda x,y: x+y, [1,2,3])
print(t)   #6,((1+2)+3)=6

t = reduce(lambda x,y: x*10+y,[1,2,3])
print(t) # ((1*10+2)*10+3)=123

filter函數(shù)

看名字,就是一個過濾的功能,對每個item調(diào)用function,只返回為True的

|  filter(function or None, iterable) --> filter object
|  
|  Return an iterator yielding those items of iterable for which function(item)
|  is true. If function is None, return the items that are true.
t = filter(lambda x: x<0,range(-5,5))
print(list(t)) #[-5, -4, -3, -2, -1]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容