P进阶_(map函数)
定义:
print(map.__doc__)
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.
说明:
创建一个迭代器,使用来自每个可迭代对象的参数计算函数。当最短的迭代用完时停止,返回一个迭代器
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
iterable -- 一个或多个序列---包含可迭代对象,字符串,列表,等
举例子
将可迭代对象,转化为str,后用列表返回
字符串类型
name1 = map(str, "12345")
name2 = map(str, (1, 2, 3, 4, 5))
name3 = map(str, [1, 2, 3, 4, 5])
print(name1) # <map object at 0x000001A8F8D949A0>
print(name2) # <map object at 0x000001A8F8D948B0>
print(name3) # <map object at 0x000001A8F8D94880>
print(list(name1)) # ['1', '2', '3', '4', '5']
print(list(name2)) # ['1', '2', '3', '4', '5']
print(list(name3)) # ['1', '2', '3', '4', '5']
函数类型
def add_demo(x):
return x * x
list_data = range(5)
res = map(add_demo, list_data)
print(res) # <map object at 0x000001F9F6A1FCA0>
print(list(res)) # [0, 1, 4, 9, 16]
lambda 使用方法
res = list(map(lambda x: x * x, range(5)))
print(res)
遍历
for i in map(lambda x:x*x,range(5)):
print(i)
# 0 1 4 9 16