详解python函数之map,Filter,Reduce
本篇文章给大家分享的是详解python函数之map,filter,reduce,内容挺不错的,希望可以帮助到有需要的朋友
1.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)) # 译者注:上面print时,加了list转换,是为了python2/3的兼容性 # 在python2中map直接返回列表,但在python3中返回迭代器 # 因此为了兼容python3, 需要list转换一下 # Output: # [0, 0] # [1, 2] # [4, 4] # [9, 6] # [16, 8]
2.Filter
顾名思义,filter过滤列表中的元素,并且返回一个由所有符合要求的元素所构成的列表,符合要求即函数映射到该元素时返回值为True. 这里是一个简短的例子:
number_list = range(-5, 5)less_than_zero = filter(lambda x: x <p style="font-size:16px;line-height:24px;margin-top:0px;margin-bottom:24px;color:rgb(64,64,64);font-family:Lato, 'proxima-nova', 'Helvetica Neue', Arial, sans-serif;background-color:rgb(252,252,252);">这个filter类似于一个for循环,但它是一个内置函数,并且更快。</p><p style="font-size:16px;line-height:24px;margin-top:0px;margin-bottom:24px;color:rgb(64,64,64);font-family:Lato, 'proxima-nova', 'Helvetica Neue', Arial, sans-serif;background-color:rgb(252,252,252);">注意:如果map和filter对你来说看起来并不优雅的话,那么你可以看看另外一章:列表/字典/元组推导式<em>。</em></p><p class="section"><br></p><h1 style="font-size:25.2px;margin-top:0px;font-family:'Roboto Slab', 'ff-tisa-web-pro', Georgia, Arial, sans-serif;">3.Reduce</h1><p style="font-size:16px;line-height:24px;margin-top:0px;margin-bottom:24px;">当需要对一个列表进行一些计算并返回结果时,Reduce 是个非常有用的函数。举个例子,当你需要计算一个整数列表的乘积时。</p><p style="font-size:16px;line-height:24px;margin-top:0px;margin-bottom:24px;">通常在 python 中你可能会使用基本的 for 循环来完成这个任务。</p><p style="font-size:16px;line-height:24px;margin-top:0px;margin-bottom:24px;">现在我们来试试 reduce:</p><pre style="font-family:monospace, serif;" class="brush:php;toolbar:false;">from functools import reduceproduct = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )# Output: 24