zoukankan      html  css  js  c++  java
  • python中map()内置函数

    1、map()内置函数有两个参数,为一个函数和一个可迭代对象,将可迭代对象的每一个元素作为函数的参数进行运算加工,直到可迭代对象的每一个元素都计算完毕。

    >>> def a(x):             ## 定义函数a()
        return 3 * x
    
    >>> a(5)
    15
    >>> temp = map(a,range(10))       ## map()一共两个参数,函数a()和可迭代对象range(10)
    >>> list(temp)
    [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
    >>> temp2 = map(a,[3,8,2,30])        ## map()一共两个参数,函数a()和可迭代对象列表
    >>> list(temp2)
    [9, 24, 6, 90]

    2、map()内置函数与lambda关键字结合

    >>> temp = map(lambda x : x * 5, range(10))   ## 使用lambda定义函数,可迭代对象range(10)
    >>> list(temp)
    [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
    >>> list(map(lambda x : x / 2, range(10)))
    [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]

    3、

    map()的第二个参数是收集参数,支持多个可迭代对象。map()会从所有可迭代对象中依次取一个元素组成一个元组,然后将元组传递给func。如果可迭代对象的长度不一致,则以较短的迭代结束为止。

    >>> def a(x,y):
        return x * y
    
    >>> a(4,8)
    32
    >>> temp = map(a,[4,8,6],[8,3,7])
    >>> list(temp)
    [32, 24, 42]
    >>> def a(x,y):
        return x * y
    
    >>> temp = map(a,[3,5,2,7,8],[6,8,9])
    >>> list(temp)
    [18, 40, 18]

    与lambda结合:

    >>> temp = map(lambda x,y,z : x * y * z, [3,2,5,7],[2,4,7,9],[8,7,3,1])
    >>> list(temp)
    [48, 56, 105, 63]
  • 相关阅读:
    深入理解Java虚拟机二之Java内存区域与内存溢出异常
    深入理解java虚拟机一之走进Java
    数据结构之链表
    Spring AOP 详解
    Spring IOC 注入方式详解 附代码
    图的广度优先遍历
    图的深度优先遍历
    MySql 中的<=>操作符
    mysql数据库explain命令用法详解
    Java虚拟机内存分配详解
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14500582.html
Copyright © 2011-2022 走看看