python 學習筆記【Map 】
阿新 • • 發佈:2019-01-09
Map
Map
會將一個函式對映到一個輸入列表的所有元素上。這是它的規範:
規範
map(function_to_apply, list_of_inputs)
大多數時候,我們要把列表中所有元素一個個地傳遞給一個函式,並收集輸出。比方說:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map
可以讓我們用一種簡單而漂亮得多的方式來實現。就是這樣:
items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, items))
大多數時候,我們使用匿名函式(lambdas)來配合map
, 所以我在上面也是這麼做的。 不僅用於一列表的輸入, 我們甚至可以用於一列表的函式!
def multiply(x): return (x*x) def add(x): return (x+x) funcs = [multiply, add] for i in range(5): value = map(lambda x: x(i), funcs) print(list(value)) # Output: # [0, 0] # [1, 2] # [4, 4] # [9, 6] # [16, 8]