Python 中 map() 函数的使用
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
由于Python 3与Python 2语法差异,导致一些函数的调用有所不同。
Python 2中使用map()函数
// python 2
def fun(x):
x = abs(x)
return x
print map(fun, [1, -2, -3, 4])
Python 3中使用map()函数
// Python 3
def fun(x):
x = abs(x)
return x
print(list(map(fun, [1, -2, -3, 4])))
如果在Python 3中直接使用map,会返回一个map对象:
<map object at 0x000002966D7DE470>
所以在Python 3中需要在map前调用list。