Python Map, Filter a

发布时间:2019-06-08 21:21:44编辑:auto阅读(1738)

    所属网站分类: python基础 > 函数


    作者:慧雅

    原文链接: http://www.pythonheidong.com/blog/article/21/

    来源:python黑洞网 www.pythonheidong.com

     

    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

     

     

关键字