python课堂整理15---map, filter,reduce函数
生活随笔
收集整理的這篇文章主要介紹了
python课堂整理15---map, filter,reduce函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、map函數
處理序列(可迭代對象)中的每一個元素,得到的結果是一個‘列表’(其實是個迭代器),該‘列表’元素個數及位置與原來一樣
理解下面這段代碼:
num_l = [1, 2, 4, 6] def add_one(x):return x + 1 #定義一個自加1的函數 def map_test(func, array):ret = []for i in array:res = func(i)ret.append(res)return retprint(map_test(add_one, num_l)) print(map_test(lambda x:x + 1, num_l)) #這樣更好用map函數實現
num_l = [1, 2, 4, 6] print(list(map(lambda x:x + 1,num_l))) #map函數得到的是可迭代對象,需要用list方法處理一下map函數也可以傳入自定義函數
num_l = [1, 2, 4, 6] def add_one(x):return x + 1 #定義一個自加1的函數 print(list(map(add_one,num_l)))用map函數處理字符串
msg = "dabai" print(list(map(lambda x: x.upper(), msg)))二、filter函數
filter遍歷序列中的每個元素,判斷每個元素得到布爾值,如果是Ture則保留下來
理解下面代碼:
movie_people = ['sb_123', 'sb_456', 'sb_789', 'dabai'] def filter_test(func, array):ret = []for i in movie_people:if not func(i):ret.append(i)return ret res = filter_test(lambda x: x.startswith('sb'), movie_people) #想把函數運行的結果保存下來就用變量接收,方便下面使用 print(res)filter內也能自定義函數
movie_people = ['sb_123', 'sb_456', 'sb_789', 'dabai'] def sb_show(x):return x.startswith('sb') def filter_test(func, array):ret = []for i in array:if not func(i):ret.append(i)return ret res = filter_test(sb_show, movie_people) #想把函數運行的結果保存下來就用變量接收,方便下面使用 print(res)用filter函數實現
movie_people = ['sb_123', 'sb_456', 'sb_789', 'dabai'] print(list(filter(lambda x: not x.startswith('sb'), movie_people)))用filter處理字典
people = [{'name':'alex','age':10000},{'name':'dabai','age':18},{'name':'sb','age':90000} ] print(list(filter(lambda x: x['age'] <= 18, people)))三、reduce函數
處理一個序列,然后把序列進行合并操作
理解下面代碼
num_l = [1, 2, 3, 100] def reduce_test(func, array):res = array.pop(0)for num in array:res = func(res, num)return resprint(reduce_test(lambda x, y : x * y,num_l)) #把列表里的值相乘可以設置一個默認的初始值
num_l = [1, 2, 3, 100] def reduce_test(func, array, init = None):if init is None:res = array.pop(0)else:res = initfor num in array:res = func(res, num)return resprint(reduce_test(lambda x, y : x * y,num_l, 100)) #把列表里的值相乘使用reduce函數,要先引入functools模塊
num_l = [1, 2, 3, 100] from functools import reduce print(reduce(lambda x,y : x * y, num_l, 100)) from functools import reduce print(reduce(lambda x,y : x + y, range(1,101)))轉載于:https://www.cnblogs.com/dabai123/p/11088575.html
總結
以上是生活随笔為你收集整理的python课堂整理15---map, filter,reduce函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试流程要点
- 下一篇: python学习笔记--迭代