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
  • 相关阅读:
    Linux常用命令2
    Linux常用命令1
    Nginx配置Kafka
    SpringBoot整合Druid
    spring boot jpa
    mybatis-plus_2
    copy data to map
    HashMap容量问题
    在SpringBoot主启动类中获取实例化的Bean
    Linux环境中Rsync增量备份文件
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11142491.html
Copyright © 2011-2022 走看看