Map,Filter,Reduce

2157 ワード

関数はプログラミング中のmap,filter,reduceである.
Map
mapは、リストのすべての要素に関数をマッピングします.例1:
items = [1, 2, 3, 4, 5]
list(map(lambda x: x**2, items)) #[1,4,9,16,25]

例2:
def multiply(x):
        return (x*x)
def add(x):
        return (x+x)

funcs = [multiply, add]
value = list(map(lambda x: x(3), funcs))
print(value)    # Output: [9, 6]

Filter
filterは関数(ルール)で、このルールに合致するすべての値を返します.例:
items = [1, 2, 3, 4, 5]
value = list(filter(lambda x: x > 3, items))
print(value)    # Output: [4, 5]

Reduce
reduceは、リストに対していくつかの計算を行い、結果を返します.例:
from functools import reduce
value = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(value)    # Output: 24