raylee2015 发表于2年前

• 发表于 2年前
• 阅读 1
• 收藏 0
• 评论 0

map函数，就是引入一个函数，然后对序列（字符串、列表、字典等）的每一个对象进行操作

1.场景：

对序列的所有对象分别加1

``````>>> aList=[1,2,3,4,5]
for x in range(len(aList)):
aList[x]+=1

>>> aList
[2, 3, 4, 5, 6]
>>>``````

``````>>> def add(x):
return x+1

>>> aList=[1,2,3,4,5]
[2, 3, 4, 5, 6]
>>>``````

``````>>> map(add,aList)
<map object at 0x0247B050>
<class 'map'>
>>>``````

``````>>> aList=[1,2,3,4,5]
[2, 3, 4, 5, 6]
>>> list(map(lambda x:x+1,aList)) <span style="font-family: Arial, Helvetica, sans-serif;">#把表达式单独嵌套在里面</span>
[2, 3, 4, 5, 6]
>>>``````

2.多序列

map除了上面支持单序列之外，它还支持多序列

``````>>> list(map(pow,[1,2,3],[1,2,3]))
[1, 4, 27]
>>> list(map(pow,[1,2,3],[1,2,3],[1,2,3]))
[0, 0, 0]
>>>``````

``````>>> list(map(pow,[1,2,3],[1,2]))
[1, 4]
>>>``````

3.模拟map

``````>>> def add(x): return x+1

>>> def test(func,aList):
res=[]
for item in aList:
res.append( func(item))
return res

>>> aList=[1,2,3,4,5]
[2, 3, 4, 5, 6]
>>>``````

------------------------------------------------------------------

×