Overview

在可迭代的物件中,套用運算式於每一個元素。

Usage

語法:map(function, iterable)

a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
mul = map(lambda x: x * 2, a)  # <map object at 0x00000242134BDDC8>
print(list(mul))  # [2, 4, 6, 8, 10]

plus = map((lambda x, y: x + y), a, b)  # <map object at 0x0000019D23EBEE88>
print(list(plus))  # [6, 6, 6, 6, 6]

map 函式也可以用 comprehension 來達到類似的功能,用推導式的寫法也能更 Pythonic,在程式的閱讀理解上更加直覺。

a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
print([(lambda i, j: i + j)(x, y) for x, y in zip(a, b)])
# [6, 6, 6, 6, 6]

Reference

Python's map(): Processing Iterables Without a Loop - Real Python