# python庫函數Map, Filter and Reduce的用法

python中有三個函數式編程極大的簡化了程序的複雜性，這裏就做一下討論和記錄。

``````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))
``````

``````'''

'''
def multiply(x):
return (x*x)
def add(x):
return (x+x)

funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)

# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]
``````

``````number_list = range(-5,5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

number_list = range(-5,5)
less_than_zero = list(filter(lambda x: x != 0, number_list))
print(less_than_zero)
``````

``````'''

'''
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num

# product = 24
``````

``````from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])

# Output: 24
``````