Python中的map函数有什么用途?

WBOY
풀어 주다: 2023-09-09 19:05:03
앞으로
3200명이 탐색했습니다.

Python中的map函数有什么用途?

在本文中,我们将学习Python中map函数的使用。

什么是map()函数?

Python的map()函数将一个函数应用于作为输入提供的迭代器中的每个项。列表、元组、集合、字典或字符串都可以用作迭代器,并且它们都返回可迭代的map对象。map()是Python的内置函数。

语法

map(function, iterator1,iterator2 ...iteratorN)
로그인 후 복사

参数

  • function - 有必要提供一个带有函数的映射,该函数将应用于迭代器的所有可用项。

  • iterator - 强制可迭代对象。它可以是列表、元组等。map() 函数接受多个迭代器对象作为参数。

返回值

map() 方法会将指定的函数应用于迭代器中的每个项目,并生成一个元组、列表或另一个可迭代的映射对象。

map() 函数如何工作?

函数和可迭代对象是map()函数的两个输入。传递给map()的函数是一个普通函数,它将遍历指定可迭代对象中的每个值。

使用带有数字列表的map()

示例

以下程序使用 Python 中的 map() 函数将 5 添加到列表中的每个元素 -

# creating a function that accepts the number as an argument
def exampleMapFunction(num):
   # adding 5 to each number in a list and returning it
   return num+5
 
# input list
inputList = [3, 5, 1, 6, 10]
 
# Passing above defined exampleMapFunction function
# and given list to the map() function
# Here it adds 5 to every element of the given list 
modifiedList = map(exampleMapFunction, inputList)
# printing the modifies list(map object)
print(modifiedList)
# converting the map object to the list and printing it 
print("Adding 5 to each element in a list using map():\n", list(modifiedList))
로그인 후 복사

输出


Adding 5 to each element in a list using map():
 [8, 10, 6, 11, 15]
로그인 후 복사

使用map()与字典

Python使用字典来实现更常见的关联数组。字典是一组键值对。它使用花括号 {} 来定义。

字典是动态的、不断变化的。可以根据需要更改和删除它们。字典项可以使用键访问,但列表元素是通过索引根据其在列表中的位置来检索的,这就是字典与列表的不同之处。

由于字典是一个迭代器,因此您可以在 map() 函数内部使用它。

示例

以下程序使用 Python 中的 map() 函数将 5 添加到字典中的每个元素 -

# creating a function that accepts the number as an argument
def exampleMapFunction(num):
   # adding 5 to each number in a dictionary and returning it
   return num + 5
 
# input Dictionary
inputDictionary = {2, 3, 4, 5, 6, 7, 8, 9}
 
# passing above defined exampleMapFunction function
# and input dictionary to the map() function
# Here it adds 5 to every element of the given dictionary 
modifiedDict = map(exampleMapFunction, inputDictionary)
# printing the modified dictionary(map object)
print(modifiedDict)
# converting the map object to the list and printing it
print("Adding 5 to each element in a dictionary using map():\n", list(modifiedDict))
로그인 후 복사

输出


Adding 5 to each element in a dictionary using map():
 [7, 8, 9, 10, 11, 12, 13, 14]
로그인 후 복사

使用 map() 函数与元组

在Python中,元组是一个由逗号分隔的元素并用圆括号括起来的对象。

示例

以下代码使用lower()和map()函数将元组中的所有项转换为小写:

# creating a function that accepts the number as an argument
def exampleMapFunction(i):
   # converting each item in tuple into lower case
   return i.lower()
 
# input tuple
inputTuple = ('HELLO', 'TUTORIALSPOINT', 'pyTHON', 'CODES')
 
# passing above defined exampleMapFunction function
# and input tuple to the map() function
# Here it converts every element of the tuple to lower case 
modifiedTuple = map(exampleMapFunction, inputTuple)
# printing the modified tuple(map object)
print(modifiedTuple)
 
print('Converting each item in a tuple to lowercase:')
# converting the map object to the list and printing it
print(list(modifiedTuple))
로그인 후 복사

输出


Converting each item in a tuple to lowercase:
['hello', 'tutorialspoint', 'python', 'codes']
로그인 후 복사

在Python中使用map()与其他函数工具

使用map()与函数工具如filter()reduce()一起,我们可以在可迭代对象上执行更复杂的变化。

使用map()和filter()函数

在某些情况下,我们必须处理可迭代的输入,并通过从输入中删除/过滤不必要的项目来返回另一个可迭代对象。在这种情况下,Python的filter()是一个明智的选择。

filter()函数返回满足函数返回true的可迭代输入项。

如果没有传递函数,则filter()将使用身份函数。这表示filter()会检查可迭代对象中的每个项的真值,并删除所有假值。

示例

以下函数结合使用filter()和map()函数过滤列表中的所有正数并返回它们的平方根 -

# importing math module
import math 
 
# creating a function that returns whether the number 
# passed is a positive number or not 
def isPositive(n): 
   return n >= 0 
 
# creating a function that filters all the positive numbers
# from the list and returns the square root of them. 
def filterSqrtofPositive(nums): 
   # filtering all the positive numbers from the list using filter()
   # and returning the square root of them using the math.sqrt and map()  
   filteredItems = map(math.sqrt, filter(isPositive, nums)) 
   # returning the list of filetred elements
   return list(filteredItems) 
 
# input list
inputList= [16, -10, 625, 25, -50, -25]
# calling the function by passing the input list 
print(filterSqrtofPositive(inputList))
로그인 후 복사

输出

[4.0, 25.0, 5.0]
로그인 후 복사

结论

Python 的 map() 函数允许您对可迭代对象执行操作。 Map() 通常用于转换和处理可迭代对象,而不需要循环。

在本文中,我们以几种数据类型为例,学习了如何在 Python 中使用 map() 方法。

위 내용은 Python中的map函数有什么用途?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!