zoukankan      html  css  js  c++  java
  • filter()和map()

    内置函数:filter()

    先看看filter的函数文档

     |  filter(function or None, iterable) --> filter object
     |  
     |  Return an iterator yielding those items of iterable for which function(item)
     |  is true. If function is None, return the items that are true.
    

    filter有两个参数,第一个参数可以是函数也可以是None,第二个参数是iterable(可迭代对象、序列,如列表、元组等)

    当第一个参数是函数时,将第二个参数的每一个元素作为函数的参数进行计算,并将返回值为ture的元素返回。

    >>> def jishu(x):
    	if x %2 == 1:
    		return x
    
    >>> filter(jishu,[1,2,3,4,5,6,7,8,9])
    <filter object at 0x000000F732728DA0>
    
    >>> list(filter(jishu,[1,2,3,4,5,6,7,8,9]))
    [1, 3, 5, 7, 9]
    

    当第一个参数是None时,返回第二参数中为Ture的值。

    >>> list(filter(None,[1,0,True,False]))
    [1, True]
    

    内置函数map()

    先看map()的函数文档

     |  map(func, *iterables) --> map object
     |  
     |  Make an iterator that computes the function using arguments from
     |  each of the iterables.  Stops when the shortest iterable is exhausted.
    

    map接受两个参数,参数一为函数,参数二为一个iiterables(到此与filter极似,但是注意map的第二个参数是*iterables,与filter有区别)

    map的作用是将第iterables中的元素依次传入函数,并将函数运行结果返回为iterable。

    >>> def 平方(x):
    	return x*x
    
    >>> list(map(平方,[1,3,5,7,9]))
    [1, 9, 25, 49, 81]
    
    #map 将 1、3、5、7、9 依次传入函数计算平方并返回值
  • 相关阅读:
    漫谈五种IO模型
    jvm调优-命令大全(jps jstat jmap jhat jstack jinfo)
    Intellij IDEA 插件开发秘籍
    二进制
    java程序员必知的 8大排序
    Redis常见问题
    BitMap位图
    编程思想
    Final修饰的字段是否可以通过反射设置值
    ORACLE 11g ORA-20000: Unable to analyze TABLE "AA"."CMP3$87651", insufficient privileges or does not exist
  • 原文地址:https://www.cnblogs.com/ginsonwang/p/5263923.html
Copyright © 2011-2022 走看看