We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results. map() returns a map object (an iterator), which we can use in other parts of our program. We can also pass the map object to the list() function, or another sequence type, to create an iterable.
我们可以使用Python内置函数map()将函数应用于可迭代项(例如list或dictionary )中的每个项目,并返回一个新的迭代器以检索结果。 map()返回一个地图对象(一个迭代器),我们可以在程序的其他部分中使用它。 我们还可以将map对象传递给list()函数或其他序列类型,以创建一个可迭代的对象。
The syntax for the map() function is as follows:
map()函数的语法如下:
map(function, iterable, [iterable 2, iterable 3, ...])
Instead of using a for, the map() function provides a way of applying a function to every item in an iterable. Therefore it can often be more performant since it is only applying the function one item at a time rather than making copies of the items into another iterable. This is particularly useful when working on programs processing large data sets. map() can also take multiple iterables as arguments to the function by sending one item from each iterable to the function at a time.
map()函数提供了一种将函数应用于可迭代对象中的每个项目的方法,而不是使用for循环 。 因此,由于每次仅将一项功能应用于一项功能,而不是将各项的副本复制到另一项中,因此通常可以提高性能。 在处理处理大数据集的程序时,这特别有用。 通过一次从每个可迭代对象向函数发送一项, map()还可以将多个可迭代对象作为函数的参数。
In this tutorial, we’ll review three different ways of working with map(): with a lambda function, with a user-defined function, and finally with a built-in function using multiple iterable arguments.
在本教程中,我们将介绍map()三种不同使用方式:使用lambda函数,使用用户定义的函数以及使用多个可迭代参数的内置函数。
The first argument to map() is a function, which we use to apply to each item. Python calls the function once for every item in the iterable we pass into map() and it returns the manipulated item within a map object. For the first function argument, we can either pass a user-defined function or we can make use of lambda functions, particularly when the expression is less complex.
map()的第一个参数是一个函数,我们将其应用于每个项目。 Python对传递给map()的可迭代项中的每一项调用一次函数,并返回map对象内的操作项。 对于第一个函数参数,我们可以传递用户定义的函数,也可以使用lambda函数,尤其是当表达式不太复杂时。
The syntax of map() with a lambda function is as follows:
带lambda函数的map()的语法如下:
map(lambda item: item[] expression, iterable)
With a list like the following, we can implement a lambda function with an expression that we want to apply to each item in our list:
使用下面的列表,我们可以使用要应用于列表中每个项目的表达式来实现lambda函数:
numbers = [10, 15, 21, 33, 42, 55]
To apply an expression against each of our numbers, we can use map() and lambda:
要对每个数字应用表达式,可以使用map()和lambda :
mapped_numbers = list(map(lambda x: x * 2 + 3, numbers))
Here we declare an item in our list as x. Then we add our expression. We pass in our list of numbers as the iterable for map().
在这里,我们将列表中的一项声明为x 。 然后添加表达式。 我们传入数字列表作为map()的可迭代对象。
In order to receive the results of this immediately we print a list of the map object:
为了立即接收结果,我们打印了map对象的列表:
print(mapped_numbers)
Output
[23, 33, 45, 69, 87, 113]
We have used list() so that the map object is returned to us as a list, rather than a less human-readable object like: <map object at 0x7fc250003a58>. The map object is an iterator over our results, so we could loop over it with for or we can use list() to turn it into a list. We’re doing this here because it’s a good way to review the results.
我们使用了list()以便将地图对象作为列表返回给我们,而不是像人类这样<map object at 0x7fc250003a58>对象: <map object at 0x7fc250003a58> 。 map对象是结果的迭代器,因此我们可以使用for对其进行循环,也可以使用list()将其转换为列表。 我们在这里这样做是因为它是查看结果的好方法。
Ultimately map() is most useful when working with large datasets, so we would likely work with the map object further, and generally would not be using a constructor like list() on them.
最终, map()在处理大型数据集时最有用,因此我们可能会进一步处理map对象,并且通常不会在其上使用类似list()的构造函数。
For smaller datasets, list comprehensions may be more suitable, but for the purposes of this tutorial we’re using a small dataset to demonstrate map().
对于较小的数据集,列表推导可能更合适,但是出于本教程的目的,我们使用一个小的数据集来演示map() 。
Similarly to a lambda we can use a function we have defined to apply to an iterable. While lambda functions are more useful to implement when you’re working with a one-line expression, user-defined functions are more appropriate when the expression grows in complexity. Furthermore, when we need to pass another piece of data to the function that you’re applying to your iterable, user-defined functions can be a better choice for readability.
与lambda类似,我们可以使用已定义的函数将其应用于可迭代对象。 当您使用单行表达式时, lambda函数对于实现更有用,而当表达式的复杂性增加时,用户定义的函数将更为合适。 此外,当我们需要将另一条数据传递给要应用于可迭代的函数时,用户定义函数可能是可读性更好的选择。
For example, in the following iterable, each item is a dictionary that contains different details about each of our aquarium creatures:
例如,在下面的迭代中,每个项目都是一个字典,其中包含有关我们每个水族馆生物的不同详细信息:
aquarium_creatures = [
{"name": "sammy", "species": "shark", "tank number": 11, "type": "fish"},
{"name": "ashley", "species": "crab", "tank number": 25, "type": "shellfish"},
{"name": "jo", "species": "guppy", "tank number": 18, "type": "fish"},
{"name": "jackie", "species": "lobster", "tank number": 21, "type": "shellfish"},
{"name": "charlie", "species": "clownfish", "tank number": 12, "type": "fish"},
{"name": "olly", "species": "green turtle", "tank number": 34, "type": "turtle"}
]
We’ve decided that all the aquarium creatures are in fact going to move into the same tank. We need to update our records to reflect that all of our creatures are moving into tank 42. To have map() access each dictionary and each key:value pair in the dictionaries, we construct a nested function:
我们已经决定所有的水族馆生物实际上都将移入同一个水箱。 我们需要更新记录,以反映出我们所有的生物都正在移入坦克42 。 为了使map()访问字典中的每个字典和每个key:value对,我们构造了一个嵌套函数:
def assign_to_tank(aquarium_creatures, new_tank_number):
def apply(x):
x["tank number"] = new_tank_number
return x
return map(apply, aquarium_creatures)
We define an assign_to_tank() function that takes aquarium_creatures and new_tank_number as parameters. In assign_to_tank() we pass apply() as the function to map() on the final line. The assign_to_tank function will return the iterator resulting from map().
我们定义一个assign_to_tank()函数,该函数将aquarium_creatures和new_tank_number作为参数。 在assign_to_tank()我们在最后一行将apply()作为函数传递给map() 。 assign_to_tank函数将返回map()生成的迭代器。
apply() takes x as an argument, which represents an item in our list — a single dictionary.
apply()将x作为参数,表示我们列表中的一个项目-一个字典。
Next we define that x is the "tank number" key from aquarium_creatures and that it should store the passed in new_tank_number. We return each item after applying the new tank number.
接下来,我们定义x为aquarium_creatures的"tank number"键,并将其存储在new_tank_number 。 应用新的油箱编号后,我们将退还每个物品。
We call assign_to_tank() with our list of dictionaries and the new tank number we want to replace for each creature:
我们用字典列表和我们要为每种生物替换的新坦克编号来调用assign_to_tank() :
assigned_tanks = assign_to_tank(aquarium_creatures, 42)
Once the function completes we have our map object stored in the assigned_tanks variable, which we turn into a list and print:
函数完成后,我们将地图对象存储在assigned_tanks变量中,将其转换为列表并打印:
print(list(assigned_tanks))
We’ll receive the following output from this program:
我们将从该程序接收以下输出:
Output
[{'name': 'sammy', 'species': 'shark', 'tank number': 42, 'type': 'fish'}, {'name': 'ashley', 'species': 'crab', 'tank number': 42, 'type': 'shellfish'}, {'name': 'jo', 'species': 'guppy', 'tank number': 42, 'type': 'fish'}, {'name': 'jackie', 'species': 'lobster', 'tank number': 42, 'type': 'shellfish'}, {'name': 'charlie', 'species': 'clownfish', 'tank number': 42, 'type': 'fish'}, {'name': 'olly', 'species': 'green turtle', 'tank number': 42, 'type': 'turtle'}]
We’ve mapped the new tank number to our list of dictionaries. Using a function that we define, we can incorporate map() to apply the function efficiently on each item of the list.
我们已将新的坦克编号映射到我们的词典列表中。 使用我们定义的函数,我们可以合并map()以将该函数有效地应用于列表的每个项目。
In the same way as lambda functions or our own defined functions, we can use Python built-in functions with map(). To apply a function with multiple iterables, we pass in another iterable name following the first one. For example, using the pow() that takes in two numbers to find the power of the base number to the provided exponent.
与lambda函数或我们自己定义的函数相同,我们可以将Python内置函数与map() 。 要应用具有多个可迭代函数的函数,我们在第一个可迭代名字后传入另一个可迭代名字。 例如,使用带两个数字的pow()函数来查找基数对所提供指数的幂。
Here we have our lists of integers that we would like to use with pow():
这是我们想要与pow()一起使用的整数列表:
base_numbers = [2, 4, 6, 8, 10]
powers = [1, 2, 3, 4, 5]
Next we pass in pow() as our function into map() and provide the two lists as our iterables:
接下来,我们将pow()作为函数传递给map()并提供两个列表作为可迭代对象:
numbers_powers = list(map(pow, base_numbers, powers))
print(numbers_powers)
map() will apply the pow() function to the same item in each list to provide the power. Therefore our results will show 2**1, 4**2, 6**3, and so on:
map()会将pow()函数应用于每个列表中的相同项以提供功能。 因此,我们的结果将显示2**1 4**2 6**3 ,依此类推:
Output
[2, 16, 216, 4096, 100000]
If we were to provide map() with an iterable that was longer than the other, map() would stop calculating once it reaches the end of the shortest iterable. In the following program we’re extending base_numbers with three additional numbers:
如果我们要给map()提供一个比另一个更长的可迭代对象,则map()到达最短可迭代对象的末尾将停止计算。 在下面的程序中,我们用另外三个数字扩展base_numbers :
base_numbers = [2, 4, 6, 8, 10, 12, 14, 16]
powers = [1, 2, 3, 4, 5]
numbers_powers = list(map(pow, base_numbers, powers))
print(numbers_powers)
As a result, nothing will change within the calculation of this program and so it will still yield the same result:
结果,此程序的计算不会发生任何变化,因此仍会产生相同的结果:
Output
[2, 16, 216, 4096, 100000]
We’ve used the map() function with a Python built-in function and have seen that it can handle multiple iterables. We’ve also reviewed that map() will continue to process multiple iterables until it has reached the end of the iterable with the fewest items.
我们已经将map()函数与Python内置函数一起使用,并且看到它可以处理多个可迭代对象。 我们还回顾了map()将继续处理多个可迭代对象,直到它以最少的项到达可迭代对象的末尾。
In this tutorial, we’ve learned the different ways of using the map() function in Python. Now you can use map() with your own function, a lambda function, and with any other built-in functions. You can also implement map() with functions that require multiple iterables.
在本教程中,我们学习了在Python中使用map()函数的不同方法。 现在,您可以将map()与您自己的函数, lambda函数以及任何其他内置函数一起使用。 您还可以使用需要多个可迭代对象的函数来实现map() 。
In this tutorial, we printed the results from map() immediately to a list format for demonstration purposes. In our programs we would typically use the returned map object to further manipulate the data.
在本教程中,我们将map()的结果立即打印为列表格式,以进行演示。 在我们的程序中,我们通常将使用返回的map对象进一步处理数据。
If you would like to learn more Python, check out our How To Code in Python 3 series and our Python topic page. To learn more about working with data sets in functional programming, check out our article on the filter().
如果您想了解更多Python,请查看我们的“ 如何使用Python 3编码”系列和Python主题页面 。 要了解有关在函数式编程中使用数据集的更多信息,请查看关于filter()函数的文章 。
翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-the-python-map-function