Python-map()函数

来源:互联网 发布:c语言线程同步的方法 编辑:程序博客网 时间:2024/05/23 00:03

首先看看map()的大概意思

>>> help(map)

Help on built-in function map in module __builtin__:

map(...)
map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).

map接收一个函数和一个可迭代对象(如列表)作为参数,用函数处理每个元素,然后返回新的列表。

例1:

>>> list1 = [1,2,3,4,5]

>>> map(float,list1)

[1.0, 2.0, 3.0, 4.0, 5.0]

>>> map(str,list1)

['1', '2', '3', '4', '5']

等价于

>>> list1

[1, 2, 3, 4, 5]

>>> for k in list1:

float(list1[k])

2.0

3.0

4.0

5.0

例2:

>>> def add(x):

return x + 100

>>> list1 = [11,22,33]

>>> map(add,list1)

[111, 122, 133]




0 0