Python Map 函數的使用
map()是一個 Python 內建函數,它允許你不需要使用循環就可以編寫簡潔的代碼。
一、Python map() 函數
這個map()函數采用以下形式:
map(function, iterable, ...)
它需要兩個必須的參數:
function - 針對每一個迭代調用的函數 iterable - 支持迭代的一個或者多個對象。在 Python 中大部分內建對象,例如 lists, dictionaries, 和 tuples 都是可迭代的。在 Python 3 中,map()返回一個與傳入可迭代對象大小一樣的 map 對象。在 Python 2中,這個函數返回一個列表 list。
讓我們看看一個例子,更好地解釋map()函數如何運作的。假如我們有一個字符串列表,我們想要將每一個元素都轉換成大寫字母。
想要實現這個目的的一種方式是,使用傳統的for循環:
directions = ['north', 'east', 'south', 'west']directions_upper = []for direction in directions: d = direction.upper() directions_upper.append(d)print(directions_upper)
輸出:
[’NORTH’, ’EAST’, ’SOUTH’, ’WEST’
使用 map() 函數,代碼將會非常簡單,非常靈活。
def to_upper_case(s): return s.upper()directions = ['north', 'east', 'south', 'west']directions_upper = map(to_upper_case, directions)print(list(directions_upper))
我們將會使用list()函數,來將返回的 map 轉換成 list 列表:
輸出:
[’NORTH’, ’EAST’, ’SOUTH’, ’WEST’]
如果返回函數很簡單,更 Python 的方式是使用 lambda 函數:
directions = ['north', 'east', 'south', 'west']directions_upper = map(lambda s: s.upper(), directions)print(list(directions_upper))
一個 lambda 函數是一個小的匿名函數。下面是另外一個例子,顯示如何創建一個列表,從1到10。
squares = map(lambda n: n*n , range(1, 11))print(list(squares))
輸出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
`range()` 函數生成一系列的整數。
二、對多個迭代對象使用map()
你可以將任意多的可迭代對象傳遞給map()函數。回調函數接受的必填輸入參數的數量,必須和可迭代對象的數量一致。
下面的例子顯示如何在兩個列表上執行元素級別的操作:
def multiply(x, y): return x * ya = [1, 4, 6]b = [2, 3, 5]result = map(multiply, a, b)print(list(result))
輸出:
[2, 12, 30]
同樣的代碼,使用 lambda 函數,會像這樣:
a = [1, 4, 6]b = [2, 3, 5]result = map(lambda x, y: x*y, a, b)print(list(result))
當提供多個可迭代對象時,返回對象的數量大小和最短的迭代對象的數量一致。
讓我們看看一個例子,當可迭代對象的長度不一致時:
a = [1, 4, 6]b = [2, 3, 5, 7, 8]result = map(lambda x, y: x*y, a, b)print(list(result))
超過的元素 (7 和 8 )被忽略了。
[2, 12, 30]
三、總結
Python 的 map()函數作用于一個可迭代對象,使用一個函數,并且將函數應用于這個可迭代對象的每一個元素。
以上就是Python Map 函數的使用的詳細內容,更多關于Python Map 函數的資料請關注好吧啦網其它相關文章!
相關文章: