Python map() 函数是一个内置函数,它允许我们在称为 mapping 的过程的帮助下转换可迭代对象中的每个项目。在此过程中,map() 函数对给定可迭代对象的每个元素应用一个函数,并返回一个新的可迭代对象。
可迭代对象是一个对象,它允许我们通过迭代它们来一次访问一个项目。可迭代的一些示例包括列表、元组、字符串等。
语法
Python map() 函数的语法如下 -
map(function, iterableObject)
参数
Python map() 函数接受以下参数 -
- function − 它表示将应用于可迭代对象的每个项目的函数。
- iterableObject − 它指定需要映射的可迭代对象或集合。
返回值
Python map() 函数返回一个新的迭代器对象。
map() 函数示例
练习以下示例来理解 Python 中 map() 函数的使用:
示例:使用 map() 函数
以下示例显示了 Python map() 函数的基本用法。在这里,我们计算指定列表中每个项目的平方。
numericLst = [2, 4, 6, 8, 10]
sqrOfLst = list(map(lambda sq: sq**2, numericLst))
print("Square of the list items:")
print(sqrOfLst)
当我们运行上述程序时,它会产生以下结果——
Square of the list items:
[4, 16, 36, 64, 100]
[4, 16, 36, 64, 100]
示例:使用 map() 将每个字符串转换为 List 的大写
在下面的代码中,我们将给定字符串列表的小写字符转换为大写。为了执行此操作,我们使用 map() 函数,将所需的函数和 list 作为参数值传递。
stringLst = ["simply", "easy", "learning", "tutorials", "point"]
newUpprCaseLst = list(map(str.upper, stringLst))
print("The list items in uppercase:")
print(newUpprCaseLst)
以下是上述代码的输出 -
The list items in uppercase:
['SIMPLY', 'EASY', 'LEARNING', 'TUTORIALS', 'POINT']
['SIMPLY', 'EASY', 'LEARNING', 'TUTORIALS', 'POINT']
示例:具有多个集合的 map() 函数
map() 函数可以一次接受多个集合或可迭代对象作为参数。在下面的代码中,我们创建两个整数列表,然后将 lambda 表达式与两个列表一起传递以执行它们的加法。
listOne = [15, 14, 13]
listTwo = [41, 43, 46]
sumOfList = list(map(lambda x, y: x + y, listOne, listTwo))
print("The addition of two lists are:")
print(sumOfList)
上述代码的输出如下 -
The list items in uppercase:
['SIMPLY', 'EASY', 'LEARNING', 'TUTORIALS', 'POINT']
['SIMPLY', 'EASY', 'LEARNING', 'TUTORIALS', 'POINT']
示例:使用 map() 查找 list 的每个字符串的长度
在下面的代码中,我们使用 map() 函数从指定列表中查找每个字符串的长度。
stringLst = ["simply", "easy", "learning", "tutorials", "point"]
lenOfLst = list(map(len, stringLst))
print("The length of each item in the List:")
print(lenOfLst)
以下是上述代码的输出 -
The length of each item in the List:
[6, 4, 8, 9, 5]
[6, 4, 8, 9, 5]