成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

Python Map 函數(shù)的使用

瀏覽:6日期:2022-07-12 18:55:24

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)文章!

標(biāo)簽: Python 編程
相關(guān)文章: