zoukankan      html  css  js  c++  java
  • python: filter, map, reduce, lambda

    filter built-in function

    filter(f,sequence)

    filter can apply the function f to each element of sequence. If return is true the element will be returned and re-organized to be a new sequence. The type of new sequence can be list/tuple/string, this depends on the input sequence type.

    >>> l=[1,2,3,4,5]
    >>> f = lambda x: True if x%2 == 0 else False
    >>> filter(f,l)
    [2, 4]
    >>> t=(1,2,3,4,5)
    >>> filter(f,t)
    (2, 4)
    

    map built-in function

    map(f, sequence)

    map will apply f to each element of sequence. The result will be returned to be a new list(Unless filter, the return will always a list).

    >>> f= lambda y : y*2
    >>> l=[1,2,3]
    >>> t=(1,2,3)
    >>> map(f,l)
    [2, 4, 6]
    >>> map(f,t)
    [2, 4, 6]
    

    reduce() built-in function

    reduce(f, sequence, start_value)

    reduce apply f to sequence by the order of the sequence. If there is a start_value, this one will be called first.

    >>> l = [1,2,3,4,5,6,7,8,9]
    >>> f = lambda x,y : x+y
    >>> reduce(f,l)
    45
    >>> reduce(f,l, 20)
    65
  • 相关阅读:
    js实现去重字符串
    js查找水仙花数
    js实现找质因数
    jQuery插件(多级菜单)
    Pycharm安装常见问题
    Python-Excel循环写入
    1110 距离之和最小 V3
    1109 01组成的N的倍数
    1393 0和1相等串
    1043 幸运号码
  • 原文地址:https://www.cnblogs.com/kramer/p/6038333.html
Copyright © 2011-2022 走看看