摘要
- lambda 爲關鍵字。filter,map,reduce爲內置函數。
- lambda:實現python中單行最小函數。
eg1:```
g = lambda x: x * 2
#相當於
def g(x):
return x*2
#1.lambda用法,冒號之前的是入參,冒號之後的是表達式,返回的值,最簡單的函數
print [(lambda x:x*x)(x)for x in range(11)]
#結果:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print (lambda x:x*x)(3)
#結果:9
g=lambda x:x*x
print g(4)
#結果:16
**
1、filter(function, sequence)
對sequence中的item依次執行function(item),將執行結果爲True的item組成一個List/String/Tuple(取決於sequence的類型)。
參數:function爲函數,sequence列表/元組/字符串
返回值:爲item列表/元組/字符串。**
**
#2.filter用法:返回執行結果爲TRUE的入參(入參是列表字符元組)
print filter(lambda x:x*x-4,range(10))
#結果:[0, 1, 3, 4, 5, 6, 7, 8, 9]
劍指offer中例題:刪除鏈表中重複的節點:
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
res = []
while pHead:
res.append(pHead.val)
pHead = pHead.next
# filter函數和map相似,但是filter是返回布爾值去去輸入列表進行判斷
res = list(filter(lambda c: res.count(c) == 1, res)) #將列表res中的元素執行lambda中的功能
2.map的用法:
對列表入參依次執行函數。入參爲列表,有多少個列表,就應該有多少個入參。
print map(lambda x:xx-4,range(10))
#結果:[-4, -3, 0, 5, 12, 21, 32, 45, 60, 77]
print map(lambda x,y:xy-4,range(3),[8,9,10])
#結果:[-4, 5, 16]
3、reduce用法:
先把sequence中第一個值和第二個值當參數傳給function,再把function的返回值和第三個值當參數傳給fuction,最終返回一個結果值
#接收的入參個數只能爲2
print reduce(lambda x,y:x*y-4,range(4))
#結果:-40
#計算0到100的和
print reduce(lambda x,y:x+y, range(101))
#結果:5050
print reduce(lambda x,y:x+y, range(101),100)
#結果:5150