首先看看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]
本文详细介绍了Python中map()函数的功能与用法,通过两个示例展示了如何使用map()函数来转换列表中的元素,包括将整数转换为浮点数和字符串类型,以及如何通过定义自定义函数来增加列表中每个元素的数值。

5636

被折叠的 条评论
为什么被折叠?



