0 语法描述

map()会根据提供的函数对指定序列做映射。

语法:

map(function, iterable, ...)

参数:

  • function函数
  • iterable一个或多个序列

第一个参数function以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的新列表。

注意:

map()函数返回一个惰性计算lazily evaluated的迭代器iteratormap对象。就像zip函数惰性计算那样。

不能通过index访问map对象的元素,也不能使用len()得到它的长度。
但我们可以强制转换map对象list

也就是说map()返回值使用一次后变为空(会在例子4中进行说明)

相对 Python2.x 提升了性能,惰性计算可以节约内存。

1 举例说明

例子1:基本用法

def square(x) :            # 计算平方数
    return x ** 2
print(map(square, [1,2,3,4,5]))   # 计算列表各个元素的平方
print(list(map(square, [1,2,3,4,5])))
for i in map(square, [1,2,3,4,5]):
    print(i)

image-20210826142006773

例子2:与匿名函数合用

print(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))   # 计算列表各个元素的平方
print(list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])))
for i in map(lambda x: x ** 2, [1, 2, 3, 4, 5]):
    print(i)

image-20210826142230122

例子3:输入两个列表

map_test = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
print(map_test)   # 计算列表各个元素的平方
for i in map_test:
    print(i)
print(list(map_test))   # 计算列表各个元素的平方

image-20210826143232392

例子4:迭代器仅可使用一次的问题

可见第二次调用变成了空list

因为迭代器Iterator会调用方法next()不断指向下一个元素,直到空,报StopIteration错误。

map_test = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
print(map_test)   # 计算列表各个元素的平方
for i in map_test:
    print(i)
print(list(map_test))   # 计算列表各个元素的平方

image-20210826143427048

规避这个惰性计算的问题,赋值的时候直接用list进行转换一下:

print("惰性计算")
map_test = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
print(list(map_test)) 
for i in map_test:
    print(i,end = " ")
print(list(map_test))  
print("规避惰性计算")
map_test = list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
print(list(map_test)) 
for i in map_test:
    print(i,end = " ")
print(list(map_test))  

image-20210826153626141

例子5 与lambda迭代dictionary列表

dict_list = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
print(list(map(lambda x : x['name'], dict_list)))
print(list(map(lambda x : x['points']*10,  dict_list)))
print(list(map(lambda x : x['name'] == "python", dict_list)))

image-20210826145027023

LAST 参考文献

Python map() 函数 | 菜鸟教程

Python的map()返回值使用一次后变为空——返回的是迭代器_光逝的博客-CSDN博客

关乎Python lambda你也看得懂 - 知乎

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐