map() 函数是 Python 内置的一个高阶函数,它接受一个函数和一个可迭代对象作为输入,并对可迭代对象中的每个元素应用该函数,最后返回一个由函数返回值组成的新的可迭代对象。
基本语法
map(function, iterable)
其中,function 是一个函数对象,可以是普通函数或匿名函数;iterable 是一个可迭代对象,例如列表、元组、集合等。
使用示例:
对列表中的每个元素求平方:
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers)) # 输出 [1, 4, 9, 16, 25]
对多个列表中的对应位置的元素进行相加:
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
summed_numbers = map(lambda x, y: x + y, numbers1, numbers2)
print(list(summed_numbers)) # 输出 [5, 7, 9]
将字符串列表转换为大写:
words = ["apple", "banana", "cherry"]
upper_words = map(str.upper, words)
print(list(upper_words)) # 输出 ["APPLE", "BANANA", "CHERRY"]
使用内置函数对列表中的元素进行处理:
numbers = [1, 2, 3, 4, 5]
absolute_numbers = map(abs, numbers)
print(list(absolute_numbers)) # 输出 [1, 2, 3, 4, 5]
混合输入赋值
a,b=map(int,input().split(" "))
print(a+b)
#输入1 2
#输出3
需要注意的是,map() 函数返回的是一个迭代器对象,如果需要使用列表形式的结果,需要通过 list() 函数进行转换。
例如:
# 创建一个整数列表
numbers = [1, 2, 3, 4, 5]
# 使用 map() 函数将每个数字转换为它们的平方,并通过 list() 函数转换为列表
squared_numbers = list(map(lambda x:x**2, numbers))
# 打印结果
print(squared_numbers)