zoukankan      html  css  js  c++  java
  • Map、Filter和Reduce函数(Python)

    Map

    map(function_to_apply, list_of_inputs)

    设有以下代码:

    >>> items = [1, 2, 3, 4, 5]
    >>> squared = []
    >>> for i in items:
    ...   squared.append(i**2)
    ... 
    >>> squared
    [1, 4, 9, 16, 25]
    

    这段代码实现的功能用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)+1, funcs))
        print(value)
    
    >>>
    [1, 1]
    [2, 3]
    [5, 5]
    [10, 7]
    [17, 9]
    

    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)
    [-5, -4, -3, -2, -1]
    

    经过_filter_函数_过滤_,条件判断为真的结果的存入list。另外值得注意的地,_filter_是_built-in_函数,运行速度更快。

    Reduce

    Reduce is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list.

    >>> from functools import reduce
    >>> product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
    >>> product
    24
    
  • 相关阅读:
    疯狂
    绝对基金的最爱,今年推荐
    蛛丝马迹中愤怒的老总
    值得作一年投资的股票
    狂牛终于被制服了,一起来享受盛宴吧(公布一些数据)
    敬而远之
    发现一庄两股
    一下表格大家好好研究吧
    怎样申购新股以及申购技巧
    股市比女人还善变
  • 原文地址:https://www.cnblogs.com/yaos/p/14014389.html
Copyright © 2011-2022 走看看