map是一個高階用法,字面意義是映射,它的作用就是把一個數據結構映射成另外一種數據結構。
map用法比較繞,最好是對基礎數據結構很熟悉了再使用,比如列表,字典,序列化這些。
map的基本語法如下:
map(function_object, iterable1, iterable2, ...)
map函數需要一個函數對象和任意數量的iterables,如list,dictionary等。它為序列中的每個元素執行function_object,並返回由函數對象修改的元素組成的列表。
示例如下:
def add2(x): return x+2 map(add2, [1,2,3,4]) # Output: [3,4,5,6]
在上面的例子中,map對list中的每個元素1,2,3,4執行add2函數並返回[3,4,5,6]
接着看看如何用map和lambda重寫上面的代碼:
map(lambda x: x+2, [1,2,3,4]) #Output: [3,4,5,6]
僅僅一行即可搞定!
使用map和lambda迭代dictionary:
dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}] map(lambda x : x['name'], dict_a) # Output: ['python', 'java'] map(lambda x : x['points']*10, dict_a) # Output: [100, 80] map(lambda x : x['name'] == "python", dict_a) # Output: [True, False]
以上代碼中,dict_a中的每個dict作為參數傳遞給lambda函數。lambda函數表達式作用於每個dict的結果作為輸出。
map函數作用於多個iterables
list_a = [1, 2, 3] list_b = [10, 20, 30] map(lambda x, y: x + y, list_a, list_b) # Output: [11, 22, 33]
這里,list_a和list_b的第i個元素作為參數傳遞給lambda函數。
在Python3中,map函數返回一個惰性計算(lazily evaluated)的迭代器(iterator)或map對象。就像zip函數是惰性計算那樣。
我們不能通過index訪問map對象的元素,也不能使用len()得到它的長度。
但我們可以強制轉換map對象為list:
map_output = map(lambda x: x*2, [1, 2, 3, 4]) print(map_output) # Output: map object: list_map_output = list(map_output) print(list_map_output) # Output: [2, 4, 6, 8]
文章首發於我的技術博客猿人學的
Python基礎教程