zoukankan      html  css  js  c++  java
  • python中的map函数

    语法

    在python3中,map是一个内置类,调用map()函数实际上是实例化map类的过程(这一点可以看出,内置类的类名可以小写)

    从源码中看,map函数有两个参数,一个是函数func(注意不是函数调用func()),另一个是可迭代的参数,*表示可以有任意多个可迭代参数

    作用

    使用可迭代对象中的每一个元素作为参数调用func函数,返回一个迭代器

    返回值

    在python3中,map()返回一个迭代器

    例子

    import sys
    
    def sq(x):
        return x ** 2
    
    it = map(sq, [1, 2, 3, 4, 5])
    while True:
        try:
            print(next(it), end=" ")
        except StopIteration:
            sys.exit()
    
    # 运行结果
    1 4 9 16 25 
    

    在map中使用lambda匿名函数

    it = map(lambda x: x ** 2, [1, 2, 3, 4, 5])
    for i in it:
        print(i, end=" ")
    
    
    # 运行结果
    1 4 9 16 25
    

    参考文章

    《Python map() 函数》

  • 相关阅读:
    改造二叉树
    汽车加油行驶问题
    [SHOI2012]回家的路
    子串
    P3558 [POI2013]BAJ-Bytecomputer
    HDU
    UVALive
    ZOJ
    HDU
    牛客小白月赛2 题解
  • 原文地址:https://www.cnblogs.com/my_captain/p/12822638.html
Copyright © 2011-2022 走看看