zoukankan      html  css  js  c++  java
  • 内置函数补充map、reduce和filter等

    map函数:映射功能

    map(function, iterable, ...):可迭代对象向函数function传入元素,并得到一个返回值.

    1 >>> map(lambda x :x+1,[1,2,3.4])
    2 [2, 3, 4.4]
    3 >>> map(lambda x :x+"_key",{"key":"value","key1":"value2"})
    4 ['key1_key', 'key_key']

    注意,在python2和python3中,map函数的返回的类型不一样。

    python2 map函数返回的是列表。

    1 >>> l = map(lambda x :x+"_key",{"key":"value","key1":"value2"})
    2 >>> l
    3 ['key1_key', 'key_key']
    4 >>> type(l)
    5 <type 'list'>

    python3中,map函数返回的是map对象,它是一个迭代器,可以调用next方法。

     1 >>> l = map(lambda x :x+"_key",{"key":"value","key1":"value2"})
     2 >>> l
     3 <map object at 0x10558c1d0>
     4 >>> next(l)
     5 'key_key'
     6 >>> 
     7 >>> next(l)
     8 'key1_key'
     9 >>> next(l)
    10 Traceback (most recent call last):
    11   File "<stdin>", line 1, in <module>
    12 StopIteration

     reduce函数:处理一个序列,并返回一个值,适合求和。python2中自带reduce函数,python3中需要导入“from functool import reduce”。

    reduce(function, iterable[, initializer ]):可迭代对象会把元素传给函数function,function会接收到两个值,如果未指定初始值initializer,则默认传0.

    python3

    1 >>> from functools import reduce 
    2 >>> l = reduce(lambda x,y:x+y,range(1,100),100) #给一个初始值100
    3 >>> l
    4 5050

    filter函数:

    filter(function, iterable):把可迭代对象变成迭代器,把每一个元素传入函数function,function会返回布尔值,结果为Ture则保留。

    python2: 

     1 >>> item_price =[
     2 ...     {"item":"apple","price":5},
     3 ...     {"item":"egg","price":4.5},
     4 ...     {"item":"water","price":1.5},
     5 ...     {"item":"fish","price":15}
     6 ... ]
     7 >>> l = filter(lambda d: d["price"]>=5,item_price)
     8 >>> type(l)
     9 <type 'list'>
    10 >>> l
    11 [{'item': 'apple', 'price': 5}, {'item': 'fish', 'price': 15}]

    python3

    >>> item_price =[
    ...     {"item":"apple","price":5},
    ...     {"item":"egg","price":4.5},
    ...     {"item":"water","price":1.5},
    ...     {"item":"fish","price":15}
    ... ]
    >>> l = filter(lambda d: d["price"]>=5,item_price)
    >>> type(l)
    <class 'filter'>
    >>> l
    <filter object at 0x10558c438>
    >>> next(l)
    {'item': 'apple', 'price': 5}
    >>> next(l)
    {'item': 'fish', 'price': 15}
    >>> next(l)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration

     pyhton3中封装了很多,类型就是类。所以我们使用map、reduce和fliter返回的都是各自的类型,且都是生成器,可以调用next方法。而python2则都是列表。

  • 相关阅读:
    Linux下安装Tomcat服务器
    记一次操蛋的:Could not find parameter map java.lang.Long
    在IDEA中使用MyBatis Generator逆向工程生成代码
    理解jquery的$.extend()、$.fn和$.fn.extend()
    在 Win10 系统下安装 JDK 及配置环境变量的方法
    怎样设置才能允许外网访问MySQL
    基于JavaMail的Java邮件发送:简单邮件发送Demo
    前端学习第57天 背景样式、精灵图、盒子模型布局细节、盒子模型案例、w3c主页
    前端学习第56天高级选择器、盒子模型、边界圆角、其他属性
    前端学习第55天 css三种引用、‘引用的优先级’、基本选择器、属性、display
  • 原文地址:https://www.cnblogs.com/greatkyle/p/6726361.html
Copyright © 2011-2022 走看看