map 函数

map() 函数的作用是:对序列 iterable 中每一个元素调用 function 函数,返回一个map对象实例。这个map对象本质上来讲是一个迭代器。

map函数基本语法:map(function, iterable)

students = [1, 2, 3, 4, 5]
# 把列表中每个元素由int变为str:
print(list(map(str, students))). # 输出['1', '2', '3', '4', '5']

# 把列表中每个元素*2
def double_func(x):
    return x* 2

print(list(map(double_func, students)))   # 输出[2, 4, 6, 8, 10]

# map+lambda表达式,将列表中元素乘2
print(list(map(lambda x: x*2, students)))   # 输出[2, 4, 6, 8, 10]

map() 函数输入多个可迭代对象

b1 = [100, 200, 300]
b2 = [1, 2, 3]

iterator = map(lambda x,y : x*y, b1, b2)
print(list(iterator))  # 输出:[100, 400, 900]

 

posted on 2024-03-12 21:04  mlllily  阅读(16)  评论(0编辑  收藏  举报