一、map函數:對序列中的元素做運算處理,得到的新序列中的元素與原序列中的元素的位置和個數一樣
引言:
1、現在有一個需求,需要將一個數字列表裏面的數字每個自增1
testlist = [1, 4, 6, 7, 9]
思路:
(1)、新建一個函數,參數爲testlist
(2)、函數體內容爲新建一個空的臨時templist
(3)、使用for循環遍歷出傳入list的每個元素
(4)、然後元素+1
(5)、將元素拼接到臨時list中
(6)、返回臨時list
具體實現:
testlist = [1, 4, 6, 7, 9]
def callist(testlist):
templist = []
for item in testlist:
templist.append(item + 1)
print(templist)
return templist
callist(testlist)
2、需求變更,除了自增功能外,我還可以自減,平方,等等操作
思路:
(1)、將計算方法提取出來到一個新的函數中
(2)、將計算方法函數當做一個參數傳遞到函數中
具體實現:
testlist = [1, 4, 6, 7, 9]
def plus_self(x):
return x + 1
def reduce_self(x):
return x - 1
def ride_self(x):
return x ** 2
def callist(func,testlist):
templist = []
for item in testlist:
templist.append(func(item))
print(templist)
return templist
callist(reduce_self, testlist)
另一種思路:
使用匿名函數:lambda
def callist(func, testlist):
templist = []
for item in testlist:
templist.append(func(item))
print(templist)
return templist
callist(lambda x: x + 1, testlist)
map函數正文:
map(func, *iterables):參數1:lambda函數和自定義處理函數;參數2:可迭代對象
上面的callist(func, testlist)函數其實就相當於map函數,下面使用map函數再實現上述功能:
maptest = list(map(lambda x: x + 1, testlist))
可以看出,使用map函數可以精簡一大部分代碼,只需要自定義函數功能和一個可迭代對象就可以實現較爲複雜的功能
二、filter函數:對序列中的元素做篩選處理
filter(function or None, iterable):參數1:lambda函數和自定義處理函數;參數2:可迭代對象
循環取出後面的可迭代對象中的元素,來交給前面的函數做一個邏輯判斷,返回一個bool值,來確定這個元素是被保留還是被捨棄
persion_name = ["dou1_mvp", "dou2", "dou3_mvp", "dou4_mvp"]
persionlist = list(filter(lambda n: not n.endswith("mvp"), persion_name))
print("使用filter得到的結果是:", persionlist)
三、reduce函數:將序列做加工處理,比如打包,壓縮
使用前需要先導入模塊:
from functools import reduce
reduce(function, sequence, initial=None):參數1,計算處理函數;參數2,序列;參數3,默認初始值
num_list = [1, 4, 6, 100]
res = reduce(lambda x, y: x + y, num_list, 5)
print("使用reduce函數得到的結果是:", res)