日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python课堂整理15---map, filter,reduce函数

發布時間:2024/1/17 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。