zoukankan      html  css  js  c++  java
  • python内置函数filter(),map(),reduce()笔记

    '''
    python reduce()函数:
    reduce()函数会对参数序列中元素进行积累。

    函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 function(有两个参数)
    先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

    语法:ruduce()
    reduce(function,iterable,initializer)
    参数:function-函数,有两个参数
    iterable--可迭代对象
    initializer--可选,初始参数
    返回值:返回函数计算结果:
    '''
    def add(x,y):
    return x+y
    print reduce(add,[1,2,3,4,5])
    >>>15
    #相当于
    print reduce(lambda x,y:x+y,[1,2,3,4,5])
    >>> 15
    '''
    python的map函数
    map()会根据提供的函数对指定序列做映射
    第一个参数function以参数序列汇总的每一个元素中调用function函数,返回包含每次 function 函数返回值的新列表。
    语法:
    map()函数语法:
    map(function,iterable,...)
    参数

    function -- 函数,有两个参数
    iterable -- 一个或多个序列

    返回值

    返回列表。
    '''
    def map_fun(x):
    return x**2
    print map(map_fun,[1,2,3,4,5])
    >>> [1,4,9,16,25]
    print map(lambda x:x**2,[1,2,3,4,5])
    >>> [1,4,9,16,25]

    '''
    Python filter() 函数
    描述:
    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

    该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判段,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
    '''
    print filter(lambda x:x%2==0,[1,2,3,4,5])

    import math
    print filter(lambda x:math.sqrt(x)%1==0,range(1,101))
    >>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


    import math
    def is_sqr(x):
    return math.sqrt(x) % 1==0
    newlist = filter(is_sqr,range(1,101))
    print newlist
    >>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


  • 相关阅读:
    bootstrap多选框
    window.open()总结
    sql游标及模仿游标操作
    表变量及临时表数据批量插入和更新 写法
    表变量类型的创建及使用
    事物及exec
    [NOI2017]蚯蚓排队
    [NOI2017]游戏
    [NOI2017]蔬菜
    luogu P4194 矩阵
  • 原文地址:https://www.cnblogs.com/papapython/p/7473794.html
Copyright © 2011-2022 走看看