map函数的使用

描述

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表

语法

map() 函数语法:

map(function,  iterable, ...)
函数名称 可迭代的

参数

  • function -- 函数
  • iterable -- 一个或多个序列

返回值

Python 2.x 返回列表。

1 def square(x) :            # 计算平方数    
2     return x ** 2
3  print(map(square, [1,2,3,4,5])) # 计算列表各个元素的平方
4 
5 
6 
7 
8 
9 >>>>>[1, 4, 9, 16, 25]
View Code

Python 3.x 返回迭代器。

#map函数原理
num_l=[1,2,10,5,3,7]
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))
------------------------------------------------------
***************************************
---------------------------------------------------------
num_l=[1,2,10,5,3,7]
res=map(lambda x:x+1,num_l)#map(map_test,num_1)
print('内置函数map,处理结果',res)###结果内置函数map,处理结果 <map object at 
print(list(res))                                                       0x000002E7CCDA6390>
View Code

猜你喜欢

转载自www.cnblogs.com/yingdongyi/p/9665927.html