描述
map() 會根據提供的函數對指定序列做映射。
第一個參數 function 以參數序列中的每一個元素調用 function 函數,返回包含每次 function 函數返回值的新列表
語法
map() 函數語法:
map(function, iterable, ...)
函數名稱 可迭代的
參數
- function -- 函數
- iterable -- 一個或多個序列
返回值
Python 2.x 返回列表。

1 def square(x) : # 計算平方數 2 return x ** 2 3 print(map(square, [1,2,3,4,5])) # 計算列表各個元素的平方 4 5 6 7 8 9 >>>>>[1, 4, 9, 16, 25]
Python 3.x 返回迭代器。

#map函數原理 num_l=[1,2,10,5,3,7] def map_test(func,array): #func=lambda x:x+1 arrary=[1,2,10,5,3,7] ret=[] for i in array: res=func(i) #add_one(i) ret.append(res) return ret print(map_test(lambda x:x+1,num_l)) ------------------------------------------------------ *************************************** --------------------------------------------------------- num_l=[1,2,10,5,3,7] res=map(lambda x:x+1,num_l)#map(map_test,num_1) print('內置函數map,處理結果',res)###結果內置函數map,處理結果 <map object at print(list(res)) 0x000002E7CCDA6390>
描述
filter() 函數用於過濾序列,過濾掉不符合條件的元素,返回一個迭代器對象,如果要轉換為列表,可以使用 list() 來轉換。
該接收兩個參數,第一個為函數,第二個為序列,序列的每個元素作為參數傳遞給函數進行判,然后返回 True 或 False,最后將返回 True 的元素放到新列表中。
filter(function, iterable)
參數
- function -- 判斷函數。
- iterable -- 可迭代對象。
返回值
返回一個迭代器對象,用list()取出列表,跟map()函數相似。