python内置函数map的介绍

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

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

语法:

map()函数语法
map(function, iterable, ......)

 

params:

function --函数

iterable --一个或者多个序列

return value

python 2 返回l列表

python 3 返回迭代器def square(x): # 计算平均数

  return x ** 2

list(map(square, [1,2,3,4,5])) # 计算列表各个元素的平方
[1,4,9,16,25]

list(map(lambda x: x ** 2, [1,2,3,,4,5]))
[1,4,9,16,25]

# 提供了两个列表,对相同位置的列表数据进行相加
list(map(lambda x, y: x + y, [1,3,5,7,9] , [2,4,6,8,10]))
[3,7,11,15,19]


list(map(lambda x, y: x +y, [1,2,3,4,5], [1,2,3,4])) # 如果元素个数不匹配则按少的位数返回
[2,4,6,8]


In [107]: list(map(lambda x, y : x + y, [1,2,3,4,5],[1,2,3,4, '9']))

# 不同类型相加则会报错

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-107-72109fcf3fb7> in <module>
----> 1 list(map(lambda x, y : x + y, [1,2,3,4,5],[1,2,3,4, '9']))


<ipython-input-107-72109fcf3fb7> in <lambda>(x, y)
----> 1 list(map(lambda x, y : x + y, [1,2,3,4,5],[1,2,3,4, '9']))


TypeError: unsupported operand type(s) for +: 'int' and 'str





 

posted @ 2020-05-14 14:54  夜晚的潜水艇  阅读(251)  评论(0)    收藏  举报