• Python map学习笔记


    map是一个高阶用法,字面意义是映射,它的作用就是把一个数据结构映射成另外一种数据结构。

    map用法比较绕,最好是对基础数据结构很熟悉了再使用,比如列表,字典,序列化这些。

    map的基本语法如下:

    map(function_object, iterable1, iterable2, ...)

    map函数需要一个函数对象和任意数量的iterables,如list,dictionary等。它为序列中的每个元素执行function_object,并返回由函数对象修改的元素组成的列表。
    示例如下:

    def add2(x):
        return x+2
    
    map(add2, [1,2,3,4])  # Output: [3,4,5,6]

    在上面的例子中,map对list中的每个元素1,2,3,4执行add2函数并返回[3,4,5,6]
    接着看看如何用map和lambda重写上面的代码:

    map(lambda x: x+2, [1,2,3,4])  #Output: [3,4,5,6]

    仅仅一行即可搞定!

    使用map和lambda迭代dictionary:

    dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
      
    map(lambda x : x['name'], dict_a) # Output: ['python', 'java']
      
    map(lambda x : x['points']*10,  dict_a) # Output: [100, 80]
    
    map(lambda x : x['name'] == "python", dict_a) # Output: [True, False]

    以上代码中,dict_a中的每个dict作为参数传递给lambda函数。lambda函数表达式作用于每个dict的结果作为输出。

    map函数作用于多个iterables

    list_a = [1, 2, 3]
    list_b = [10, 20, 30]
      
    map(lambda x, y: x + y, list_a, list_b) # Output: [11, 22, 33]

    这里,list_a和list_b的第i个元素作为参数传递给lambda函数。

    在Python3中,map函数返回一个惰性计算(lazily evaluated)的迭代器(iterator)或map对象。就像zip函数是惰性计算那样。
    我们不能通过index访问map对象的元素,也不能使用len()得到它的长度。
    但我们可以强制转换map对象为list:

    map_output = map(lambda x: x*2, [1, 2, 3, 4])
    print(map_output) # Output: map object: 
    
    
    
    list_map_output = list(map_output)
    
    print(list_map_output) # Output: [2, 4, 6, 8]
    文章首发于我的技术博客猿人学的Python基础教程
  • 相关阅读:
    PHP远程下载图片,微信头像存到本地,本地图片转base64
    jQuery Validate自定义错误信息,自定义方法
    创建自己的composer包
    js,JQ获取短信验证码倒计时
    JQ JS复制到剪贴板
    js,JQuery 生成二维码
    js,JQuery实现,带筛选,搜索的select
    HTML5拖放牛刀小试
    HTML5上传图片预览功能
    一次dropzone体验
  • 原文地址:https://www.cnblogs.com/amiza/p/10224547.html
Copyright © 2020-2023  润新知