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