map函数
map函数
#处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样
num_l=[1,2,10,5,3,7]
num1_l=[1,2,10,5,3,7]
ret=[]
for i in num_l:
ret.append(i**2)
print(ret)
def map_test(array):
ret=[]
for i in num_l:
ret.append(i**2)
return ret
ret=map_test(num_l)
rett=map_test(num1_l)
print(ret)
print(rett)
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
[1, 4, 100, 25, 9, 49]
[1, 4, 100, 25, 9, 49]
[1, 4, 100, 25, 9, 49]
num_l=[1,2,10,5,3,7]
#lambda x:x+1
def add_one(x):
return x+1
#lambda x:x-1
def reduce_one(x):
return x-1
#lambda x:x**2
def pf(x):
return x**2
func,代表上面的方法,arrary代表列表
def map_test(func,array):
ret=[]
for i in num_l:
res=func(i) #add_one(i)
ret.append(res)
return ret
print(map_test(add_one,num_l))
print(map_test(lambda x:x+1,num_l))
上面的这两个输出一样
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
[2, 3, 11, 6, 4, 8]
[2, 3, 11, 6, 4, 8]
# print(map_test(reduce_one,num_l))
# print(map_test(lambda x:x-1,num_l))
# print(map_test(pf,num_l))
# print(map_test(lambda x:x**2,num_l))
#终极版本
def map_test(func,array): #func=lambda x:x+1 arrary=[1,2,10,5,3,7]
ret=[]
for i in array:
res=func(i) #add_one(i)
ret.append(res)
return ret
print(map_test(lambda x:x+1,num_l))
map用的方法,map(处理方法,可迭代对象)
num_l=[1,2,10,5,3,7]
res=map(lambda x:x+1,num_l)
print('内置函数map,处理结果',res)
打印出来了一段内存地址
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
内置函数map,处理结果 <map object at 0x000001D4B06DEAC8>
for i in res:
print(i)
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
2
3
11
6
4
8
print(list(res))
必须用list函数,不然会出现上面的结果
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
内置函数map,处理结果 <map object at 0x0000018E4509EAC8>
[2, 3, 11, 6, 4, 8]
print('传的是有名函数',list(map(reduce_one,num_l)))
也可以直接用函数处理方法,也可以使用lambda逻辑精简,但是如果比较得复杂用函数比较得好
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
传的是有名函数 [0, 1, 9, 4, 2, 6]
msg='linhaifeng'
print(list(map(lambda x:x.upper(),msg)))

浙公网安备 33010602011771号