Map
Map
applies a function to all the items in an input_list.
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))
二者返回的结果相同,显然map
更为简单。
map
应用的对象list_of_inputs
不仅仅可以是list这样的数据,还可以是函数,例如
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]
Filter
filter
creates a list of elements for which a function returns true。
例子:
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
filter
是内置函数,所以效率很高,很快。
Reduce
Reduce
is a really useful function for performing some computation on a list and returning the result.
比如如果想计算整数连乘,如4!
,如果使用普通的for循环来计算,效率会很差。
此时可以使用reduce
:
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
# Output: 24