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 依次传入函数计算平方并返回值
  • 相关阅读:
    第二阶段团队项目冲刺第三天
    第二阶段团队项目冲刺第二天
    第二阶段团队项目冲刺第一天
    第二次冲刺站立会议05
    第二次冲刺站立会议04
    第二次冲刺站立会议03
    第二次冲刺站立会议02
    第二次冲刺站立会议01
    第二次冲刺计划会议
    cnblogs.com的用户体验
  • 原文地址:https://www.cnblogs.com/ginsonwang/p/5263923.html
Copyright © 2011-2022 走看看