zoukankan      html  css  js  c++  java
  • python内置函数map的介绍

    map()会根据提供的函数指定序列做映射

    第一个参数function以参数序列中的每一个元素调用function函数,返回包含每次function函数的新列表

    语法:

    map()函数语法
    map(function, iterable, ......)

    params:

    function --函数

    iterable --一个或者多个序列

    return value

    python 2 返回l列表

    python 3 返回迭代器def square(x): # 计算平均数

      return x ** 2

    list(map(square, [1,2,3,4,5])) # 计算列表各个元素的平方
    [1,4,9,16,25]

    list(map(lambda x: x ** 2, [1,2,3,,4,5]))
    [1,4,9,16,25]

    # 提供了两个列表,对相同位置的列表数据进行相加
    list(map(lambda x, y: x + y, [1,3,5,7,9] , [2,4,6,8,10]))
    [3,7,11,15,19]


    list(map(lambda x, y: x +y, [1,2,3,4,5], [1,2,3,4])) # 如果元素个数不匹配则按少的位数返回
    [2,4,6,8]


    In [107]: list(map(lambda x, y : x + y, [1,2,3,4,5],[1,2,3,4, '9']))

    # 不同类型相加则会报错

    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    <ipython-input-107-72109fcf3fb7> in <module>
    ----> 1 list(map(lambda x, y : x + y, [1,2,3,4,5],[1,2,3,4, '9']))

    
    

    <ipython-input-107-72109fcf3fb7> in <lambda>(x, y)
    ----> 1 list(map(lambda x, y : x + y, [1,2,3,4,5],[1,2,3,4, '9']))

    
    

    TypeError: unsupported operand type(s) for +: 'int' and 'str





  • 相关阅读:
    简单了解Linux文件目录
    解决GitLab的Forbidden和Nginx启动失败
    浅谈apidoc的使用
    Linux安装apidoc
    DevExpress的GridControl的实时加载数据解决方案(取代分页)
    Devexpress使用经验1
    ajax下载文件
    var str = "1,21,".TrimEnd(',');
    MSSQ调优所需用的语句
    js中替换返回json中的空格为&nbsp;
  • 原文地址:https://www.cnblogs.com/tangda/p/12888635.html
Copyright © 2011-2022 走看看