Python map() 函式



Python 的 map() 函式 是一個 內建函式,它允許我們使用稱為對映的過程來轉換迭代物件中的每個專案。在這個過程中,map() 函式對給定迭代物件的每個元素應用一個函式,並返回一個新的迭代器物件。

迭代器是一個允許我們透過迭代來一次訪問一個專案的物件。一些迭代器的例子包括 列表元組字串 等等。

語法

Python map() 函式的語法如下:

map(function, iterableObject)

引數

Python map() 函式接受以下引數:

  • function − 它表示一個將應用於迭代物件中每個專案的函式。

  • iterableObject − 它指定需要對映的迭代器或集合。

返回值

Python map() 函式返回一個新的迭代器物件。

map() 函式示例

練習以下示例以瞭解如何在 Python 中使用 map() 函式

示例:map() 函式的使用

以下示例顯示了 Python map() 函式的基本用法。在這裡,我們計算指定列表中每個專案的平方。

numericLst = [2, 4, 6, 8, 10]
sqrOfLst = list(map(lambda sq: sq**2, numericLst))
print("Square of the list items:")
print(sqrOfLst)

執行上述程式時,它會產生以下結果:

Square of the list items:
[4, 16, 36, 64, 100]

示例:使用 map() 將列表中每個字串轉換為大寫

在下面的程式碼中,我們將給定字串列表的小寫字元轉換為大寫。為了執行此操作,我們透過傳遞所需的函式和列表作為引數值來使用 map() 函式。

stringLst = ["simply", "easy", "learning", "tutorials", "point"]
newUpprCaseLst = list(map(str.upper, stringLst))
print("The list items in uppercase:")
print(newUpprCaseLst)

以上程式碼的輸出如下:

The list items in uppercase:
['SIMPLY', 'EASY', 'LEARNING', 'TUTORIALS', 'POINT']

示例:map() 函式與多個集合

map() 函式可以一次接受多個集合或迭代器作為引數。在下面的程式碼中,我們建立了兩個整數列表,然後將 lambda 表示式與這兩個列表一起傳遞以執行它們的加法。

listOne = [15, 14, 13]
listTwo = [41, 43, 46]
sumOfList = list(map(lambda x, y: x + y, listOne, listTwo))
print("The addition of two lists are:")
print(sumOfList)

以上程式碼的輸出如下:

The addition of two lists are:
[56, 57, 59]

示例:使用 map() 查詢列表中每個字串的長度

在以下程式碼中,我們使用 map() 函式查詢指定列表中每個字串的長度。

stringLst = ["simply", "easy", "learning", "tutorials", "point"]
lenOfLst = list(map(len, stringLst))
print("The length of each item in the List:")
print(lenOfLst)

以上程式碼的輸出如下:

The length of each item in the List:
[6, 4, 8, 9, 5]
python_built_in_functions.htm
廣告