Python Map 函數(shù)的使用
map()是一個 Python 內(nèi)建函數(shù),它允許你不需要使用循環(huán)就可以編寫簡潔的代碼。
一、Python map() 函數(shù)
這個map()函數(shù)采用以下形式:
map(function, iterable, ...)
它需要兩個必須的參數(shù):
function - 針對每一個迭代調(diào)用的函數(shù) iterable - 支持迭代的一個或者多個對象。在 Python 中大部分內(nèi)建對象,例如 lists, dictionaries, 和 tuples 都是可迭代的。在 Python 3 中,map()返回一個與傳入可迭代對象大小一樣的 map 對象。在 Python 2中,這個函數(shù)返回一個列表 list。
讓我們看看一個例子,更好地解釋map()函數(shù)如何運作的。假如我們有一個字符串列表,我們想要將每一個元素都轉(zhuǎn)換成大寫字母。
想要實現(xiàn)這個目的的一種方式是,使用傳統(tǒng)的for循環(huán):
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() 函數(shù),代碼將會非常簡單,非常靈活。
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()函數(shù),來將返回的 map 轉(zhuǎn)換成 list 列表:
輸出:
[’NORTH’, ’EAST’, ’SOUTH’, ’WEST’]
如果返回函數(shù)很簡單,更 Python 的方式是使用 lambda 函數(shù):
directions = ['north', 'east', 'south', 'west']directions_upper = map(lambda s: s.upper(), directions)print(list(directions_upper))
一個 lambda 函數(shù)是一個小的匿名函數(shù)。下面是另外一個例子,顯示如何創(chuàng)建一個列表,從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()` 函數(shù)生成一系列的整數(shù)。
二、對多個迭代對象使用map()
你可以將任意多的可迭代對象傳遞給map()函數(shù)。回調(diào)函數(shù)接受的必填輸入?yún)?shù)的數(shù)量,必須和可迭代對象的數(shù)量一致。
下面的例子顯示如何在兩個列表上執(zhí)行元素級別的操作:
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 函數(shù),會像這樣:
a = [1, 4, 6]b = [2, 3, 5]result = map(lambda x, y: x*y, a, b)print(list(result))
當(dāng)提供多個可迭代對象時,返回對象的數(shù)量大小和最短的迭代對象的數(shù)量一致。
讓我們看看一個例子,當(dāng)可迭代對象的長度不一致時:
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]
三、總結(jié)
Python 的 map()函數(shù)作用于一個可迭代對象,使用一個函數(shù),并且將函數(shù)應(yīng)用于這個可迭代對象的每一個元素。
以上就是Python Map 函數(shù)的使用的詳細(xì)內(nèi)容,更多關(guān)于Python Map 函數(shù)的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python GUI庫圖形界面開發(fā)之PyQt5動態(tài)(可拖動控件大小)布局控件QSplitter詳細(xì)使用方法與實例2. vue跳轉(zhuǎn)頁面常用的幾種方法匯總3. 父div高度不能自適應(yīng)子div高度的解決方案4. react拖拽組件react-sortable-hoc的使用5. CSS清除浮動方法匯總6. 不要在HTML中濫用div7. js開發(fā)中的頁面、屏幕、瀏覽器的位置原理(高度寬度)說明講解(附圖)8. XML 非法字符(轉(zhuǎn)義字符)9. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)10. ASP動態(tài)include文件
