Python中map()函数浅析

通过Python中help可以查看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]




参考博客:http://my.oschina.net/zyzzy/blog/115096



你可能感兴趣的:(机器学习实战)