zoukankan      html  css  js  c++  java
  • python学习-28 map函数

    1.

    num_1 = [10,2,3,4]
    
    def map_test(array):
        ret = []
        for i in num_1:
            ret.append(i**2)     # 列表里每个元素都平方
        return ret
    res = map_test(num_1)
    print(res)

    运行结果:

    [100, 4, 9, 16]
    
    Process finished with exit code 0

    2.也可以用lambda

    num_1 = [10,2,3,4]
    
    def add_one(x):                       #  用匿名函数就不用定义这里
        return x+1
    def reduce_one(x):                    #  用匿名函数就不用定义这里
        return x-1
    
    def map_test(func,array):
        ret = []
        for i in array:
           res= func(i)
           ret.append(res)
        return ret
    
    print(map_test(add_one,num_1))
    print(map_test(lambda x:x+1,num_1))          # 也可以用 直接用匿名函数,就不用定义前面那些函数了
    
    print(map_test(reduce_one,num_1))
    print(map_test(lambda x:x-1,num_1))           # 匿名函数
    
    print(map_test(lambda x:x**2,num_1))          # 匿名函数

    运行结果:

    [11, 3, 4, 5]
    [11, 3, 4, 5]
    [9, 1, 2, 3]
    [9, 1, 2, 3]
    [100, 4, 9, 16]
    
    Process finished with exit code 0

    3. map函数 将字符串改成大写

    msg = 'abc'
    res = list(map(lambda  x:x.upper(),msg))
    print(res)

    运行结果:

    ['A', 'B', 'C']
    
    Process finished with exit code 0
  • 相关阅读:
    sql
    po bo vo java bean
    jdk面试
    Bean 参数时间 设置
    kafka demo
    spring注解 动态修改注解的值
    参考资料
    Centos 编译带调试信息的libevent
    mysql 库表整体相关查询
    MySQL安装(linux)
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11142491.html
Copyright © 2011-2022 走看看