Python Map 函数的使用函数的使用
主要介绍了Python Map 函数的使用,帮助大家更好的理解和学习python,感兴趣的朋友可以了解下
map()是一个 Python 内建函数,它允许你不需要使用循环就可以编写简洁的代码。
一、一、Python map() 函数函数
这个map()函数采用以下形式:
map(function, iterable, ...)
它需要两个必须的参数:
function - 针对每一个迭代调用的函数
iterable - 支持迭代的一个或者多个对象。在 Python 中大部分内建对象,例如 lists, dictionaries, 和 tuples 都是可迭代的。
在 Python 3 中,map()返回一个与传入可迭代对象大小一样的 map 对象。在 Python 2中,这个函数返回一个列表 list。
让我们看看一个例子,更好地解释map()函数如何运作的。假如我们有一个字符串列表,我们想要将每一个元素都转换成大写
字母。
想要实现这个目的的一种方式是,使用传统的for循环:
directions = ["north", "east", "south", "west"]
directions_upper = []
for direction in directions:
d = direction.upper()
directions_upper.append(d)
print(directions_upper)
输出:
['NORTH', 'EAST', 'SOUTH', 'WEST'
使用 map() 函数,代码将会非常简单,非常灵活。
def to_upper_case(s):
return s.upper()
directions = ["north", "east", "south", "west"]
directions_upper = map(to_upper_case, directions)
print(list(directions_upper))
我们将会使用list()函数,来将返回的 map 转换成 list 列表:
输出:
['NORTH', 'EAST', 'SOUTH', 'WEST']
如果返回函数很简单,更 Python 的方式是使用 lambda 函数:
directions = ["north", "east", "south", "west"]
directions_upper = map(lambda s: s.upper(), directions)
print(list(directions_upper))
一个 lambda 函数是一个小的匿名函数。
下面是另外一个例子,显示如何创建一个列表,从1到10。
squares = map(lambda n: n*n , range(1, 11))
print(list(squares))
输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
`range()` 函数生成一系列的整数。
二、对多个迭代对象使用二、对多个迭代对象使用map()
评论0