zoukankan      html  css  js  c++  java
  • Python map() 函数

    描述

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

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

    语法

    map() 函数语法:

    map(function, iterable, ...)
    

    参数

    • function -- 函数
    • iterable -- 一个或多个序列

    返回值

    Python 2.x 返回列表。

    Python 3.x 返回迭代器。

    实例

    以下实例展示了 map() 的使用方法:

    def square(x) :            # 计算平方数
        return x ** 2
    
    list(map(square, [1,2,3,4,5]))  # 计算列表各个元素的平方
    Out[106]: [1, 4, 9, 16, 25]
    
    list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))  # 使用 lambda 匿名函数
    Out[107]: [1, 4, 9, 16, 25]
    
    # 提供了两个列表,对相同位置的列表数据进行相加
    list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
    Out[109]: [3, 7, 11, 15, 19]
    
    #创建一个数据框
    df = pd.DataFrame({'m':[1,2,3,4],'k':[5,6,7,8]})
    
    #定义平方函数
    def square(x) :            # 计算平方数
        return x ** 2
    
    # 计算列表各个元素的平方
    df['m'].map(square) 
    Out[112]: 
    0     1
    1     4
    2     9
    3    16
    Name: m, dtype: int64
    
    # 使用 lambda 匿名函数
    df['m'].map(lambda x: x ** 2)  
    Out[113]: 
    0     1
    1     4
    2     9
    3    16
    Name: m, dtype: int64
    
    # 对相同位置的列表数据进行相加
    dataset = list(map(lambda x,y: x + y,df['m'],df['k']))
    dataset
    Out[116]: [6, 8, 10, 12]
    

      

    转载:http://www.runoob.com/python/python-func-map.html

  • 相关阅读:
    少壮不努力,老大徒伤悲
    吾日三省吾身
    记录生活
    为人处世
    时间不等人
    博客两年记忆
    抬起头吧
    下一步计划
    寻找遗失的平静
    暑假第二十六测
  • 原文地址:https://www.cnblogs.com/Christina-Notebook/p/10173062.html
Copyright © 2011-2022 走看看