from collections.abc import Iterator, Iterable
from icecream import ic
list1 = [1, 2, 3]
list2 = [3, 4, 5, 6, 7]
def func1(x):
return x+1
def func2(x, y):
return x+y
# Map集合是以 键值对<key , value> 保存数据,key值具有唯一性
# map()函数返回的是一个新的对象,不会改变原有对象。
a = map(func1, list1) # 生成一个迭代器
"""
查看源码:
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
"""
print(a)
ic(isinstance(a, Iterable)) # 可迭代
ic(isinstance(a, Iterator)) # 是迭代器
for i in a: # 用for循环遍历迭代器,输出值
print(i)
print(list(a)) # 遍历结束之后,迭代器即为空,无元素!!!
b = map(func2, list1, list2) # func2有两个参数,故需传入两个生成器。
for i in b:
print(i) # Stops when the shortest iterable is exhausted.
list3 = [100, 100]
c = map(lambda x, y, z: x+y+z, list1, list2, list3) # 结合lambda表达式使用 map函数
for i in c:
print(i)
python中map函数的使用
最新推荐文章于 2022-06-30 22:13:09 发布