Skip to content

[Python] 使用 map() 函式來迭代輸入參數給函式

Last Updated on 2021-05-12 by Clay

Python 當中的 map() 使用方法非常簡單,簡單到幾乎不需要任何說明。不過 map() 這個函式使用的地方還滿多的,故還是稍微紀錄起來。


map() 使用方法

map() 的使用方法,基本上是 map(function, iterable) 就好。 function 輸入我們要使用的函數, iterable 輸入我們要迭代輸入的對象,比如說一個 List。

順帶一提,在 Python3 當中,map() 返回的是一個可迭代的類別,我們來看段簡單的 sample code:

def add(x):
    return x+1

input = [1, 2, 3, 4, 5]
output = map(add, input)
print(output)



Output:

<map object at 0x00000228D75E96A0>

可以看到,我們在 map() 先輸入的是我們先定義好的 add() function,然後後面輸入 [1-5] 的陣列。但最後返回的結果卻是一個可迭代對象,為此,我們可能需要將其轉成 List 的資料型態。

def add(x):
    return x+1

input = [1, 2, 3, 4, 5]
output = list(map(add, input))
print(output)



Output:

[2, 3, 4, 5, 6]

我們這次就可以看到 map() 返回的 add() 結果。

另外,使用 lambda 匿名函式搭配 map() 也是相當常見的。

input = [1, 2, 3, 4, 5]
output = list(map(lambda x: x+1, input))
print(output)



Output:

[2, 3, 4, 5, 6]

我們可以看到一樣的結果。那麼以上,就是 Python 當中 map() 函式的使用方法。

Tags:

Leave a Reply取消回覆

Exit mobile version