当前位置: 移动技术网 > IT编程>脚本编程>Python > Python Map, Filter and Reduce

Python Map, Filter and Reduce

2019年05月28日  | 移动技术网IT编程  | 我要评论

蛇胆疮,不疯魔不成活txt,网游之帝国崛起

所属网站分类: python基础 > 


作者:慧雅

原文链接: 

来源:python黑洞网 

 

map, filter and reduce

这三个功能有助于编程的提升。我们将逐一讨论它们并了解它们的用例。

 

map

map将函数应用于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))
我们甚至可以拥有一系列功能,而不是输入列表!

 

 

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创建一个函数返回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]

过滤器类似于for循环,但它是内置函数,速度更快。

注意:如果map和filter看起来不厉害,那么您可以阅读有关list/dict/tuple部分的内容。

reduce

reduce是一个非常有用的函数,用于在列表上执行某些计算并返回结果。它将滚动计算应用于列表中的连续值对。例如,如果要计算整数列表的乘积。

因此,在python中执行此任务的正常方法是使用基本for循环:

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

# product = 24
现在让我们尝试使用reduce:

 

 

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

# output: 24

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网