python中reduce
介绍 (Introduction)
Python is an object-oriented programming (OOP) language. However, it provides some tools that provide a functional programming style. Some of these tools include the map(), filter(), and reduce() functions. In this tutorial, we will explore the reduce() function and unravel the versatility and usefulness that it provides.
Python是一种面向对象的编程(OOP)语言。 但是,它提供了一些提供功能性编程风格的工具。 其中一些工具包括map(),filter()和reduce()函数。 在本教程中,我们将探索reduce()函数并阐明其提供的多功能性和实用性。
使用For循环 (Using a For Loop)
The best way to introduce the reduce() function is to start with a problem and attempt to solve it the old-fashioned way, using a for loop. Then we can attempt the same task using the reduce function.
引入reduce()函数的最佳方法是从问题开始,然后尝试使用for循环以老式方式解决它。 然后,我们可以使用reduce函数尝试相同的任务。
Let’s say that we have a list of numbers and we want to return their product. In other words, we want to multiply all the numbers in the list together and return that single value. We can accomplish this using a for loop:
假设我们有一个数字列表,我们想返回它们的乘积。 换句话说,我们希望将列表中的所有数字相乘并返回该单个值。 我们可以使用for循环完成此操作:
We have our list of numbers, num_list. We want to multiply the numbers in this list together and get their product. We create the variable product and set it equal to 1. We then loop through num_list using a for loop, and we multiply each number by the result of the previous iteration. After looping through num_list, the product, or the accumulator, will equal 120, which is the product of all the numbers in the list.
我们有数字列表 num_list 。 我们想将这个列表中的数字相乘得到它们的乘积。 我们创建变量 积 并将其设置为1。然后 使用for循环 遍历 num_list ,然后将每个数字乘以上一次迭代的结果。 遍历 num_list之后 , 乘积 或累加器将等于120,这是列表中所有数字的乘积。
减少功能 (Reduce Function)
It turns out that we can accomplish the above task using the reduce function instead of a for loop. The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable (such as a list). The third argument, which is an initializer, is optional and thus we will discuss it later on.
事实证明,我们可以使用reduce函数而不是for循环来完成上述任务。 reduce函数可以接受三个参数,其中两个参数是必需的。 两个必需的参数是:一个函数(它本身带有两个参数)和一个可迭代的(例如列表)。 第三个参数是一个初始化程序,它是可选的,因此我们将在后面讨论。
reduce(function, iterable[, initializer])
reduce(函数,可迭代[,初始值设定项])
导入减少 (Importing Reduce)
The reduce function is in the module functools, which contains higher-order functions. Higher-order functions are functions that act on or return other functions. Therefore, in order to use the reduce function, we either need to import the entire functools module, or we can import only the reduce function from functools:
reduce函数位于functools模块中,该模块包含高阶函数。 高阶函数是作用于或返回其他函数的函数。 因此,为了使用reduce函数,我们要么需要导入整个functools模块,要么只能从functools中导入reduce函数:
import functoolsfrom functools import reduce
Note: if we import functools, we would need to access the reduce function like so: functools.reduce(arguments). If we import the reduce function only from the functools module, we can access the reduce function by just typing reduce(arguments).
注意:如果导入functools,则需要像以下这样访问reduce函数:functools.reduce(arguments)。 如果仅从functools模块导入reduce函数,则只需键入reduce(arguments)就可以访问reduce函数。
探索约简功能 (Exploring the Reduce Function)
As previously noted, the reduce function takes in two required arguments: a function and an iterable. In order to avoid confusion between the reduce function and the function it takes in as an argument, I will refer to the reduce function as just reduce.
如前所述,reduce函数接受两个必需的参数:函数和可迭代。 为了避免reduce函数与其作为参数接受的函数之间的混淆,我将reduce函数称为reduce 。
The first argument that reduce takes in, the function, must itself take in two arguments. Reduce will then apply this function cumulatively to the elements of the iterable (from left to right), and reduces it to a single value.
函数的reduce传入的第一个参数必须本身接受两个参数。 然后,Reduce将将此函数累积地应用于可迭代的元素(从左到右),并将其减小为单个值。
Let’s look at an example:
让我们看一个例子:
Let’s say the iterable we use is a list, such as num_list from the above example:
假设我们使用的可迭代对象是一个列表,例如上例中的num_list :
num_list = [1,2,3,4,5]
And the function we use as the first argument for reduce is the following:
我们用作reduce的第一个参数的函数如下:
def prod(x, y):
return x * y
This prod function takes in two arguments: x and y. It then returns their product, or x * y.
此prod函数采用两个参数:x和y。 然后返回其乘积,即x * y。
Let’s pass in the prod function and num_list as our function and iterable, respectively, to reduce:
让我们分别将prod函数和num_list传递为我们的函数和可迭代的函数,以减少:
from functools import reduceproduct = reduce(prod, num_list)
Our iterable object is num_list, which is the list: [1,2,3,4,5]. Our function, prod, takes in two arguments, x and y. Reduce will start by taking the first two elements of num_list, 1 and 2, and passes them in to our prod function as the x and y arguments. The prod function returns their product, or 1 * 2, which equals 2. Reduce will then use this accumulated value of 2 as the new or updated x value, and uses the next element in num_list, which is 3, as our new or updated y value. It then sends these two values (2 and 3) as x and y to our prod function, which then returns their product, 2 * 3, or 6. This 6 will then be used as our new or updated x value, and the next element in num_list will be used as our new or updated y value, which is 4. It then sends 6 and 4 as our x and y values to the prod function, which returns 24. Thus, our new x value is 24, and our new y value is the next element from num_list, or 5. These two values are passed to the prod function as our x and y values, and prod returns their product, 24 * 5, which equals 120. Thus, reduce took an iterable object, in this case num_list, and reduced it down to a single value, 120. This value is then assigned to the variable product. In other words, the x argument gets updated with the accumulated value, and the y argument gets updated from the iterable.
我们的可迭代对象是num_list ,它是列表:[1,2,3,4,5]。 我们的函数prod接受两个参数x和y。 Reduce将首先采用num_list ,1和2的前两个元素,并将它们作为x和y参数传递到我们的prod函数中。 prod函数返回其乘积,即1 * 2,等于2。然后reduce将使用此累积值2作为新的或更新的x值,并使用num_list中的下一个元素3作为新的或更新的y值。 然后将这两个值(2和3)作为x和y发送到我们的prod函数,然后返回它们的乘积2 * 3或6。这6将用作我们的新值或更新的x值,下一个将用作下一个num_list中的元素将用作新的或更新的y值,即4。然后将6和4作为x和y值发送到prod函数,该函数返回24。因此,我们的新x值为24,而我们的x新y值是num_list或5中的下一个元素。这两个值作为我们的x和y值传递到prod函数,并且prod返回其乘积24 * 5,等于120。因此,reduce采取了一个可迭代的对象,在这种情况下为num_list ,并将其减小为单个值120。然后将该值分配给变量积。 换句话说,x参数将使用累加值进行更新,而y参数则从可迭代对象进行更新。
第三论点:初始化器 (Third Argument: Initializer)
Remember how we said that reduce can take in an optional third argument, the initializer? The default value for it is None. If we pass in an initializer, it will be used as the first x value by reduce (instead of x being the first element of the iterable). So if we passed in the number 2 in the above example as the initializer:
还记得我们说过reduce可以接受可选的第三个参数,即初始化器吗? 其默认值为“无”。 如果我们传入一个初始化器,它将通过reduce用作第一个x值(而不是x是可迭代的第一个元素)。 因此,如果我们在上面的示例中将数字2传递为初始化程序:
product = reduce(prod, num_list, 2)print(product) #240
Then the first two values or arguments for x and y will be 2 and 1, respectively. All subsequent steps will be the same. In other words, the initializer is placed before the elements of our iterable in the calculation.
然后,x和y的前两个值或自变量分别为2和1。 随后的所有步骤将相同。 换句话说,在计算中将初始化程序放置在我们可迭代的元素之前。
使用Lambda表达式 (Using Lambda Expressions)
Instead of passing in prod as the function in the above example, we can instead use a lambda expression (or anonymous function) to significantly shorten our code:
除了在上面的示例中将prod作为函数传递外,我们还可以使用lambda表达式(或匿名函数)来大大缩短我们的代码:
product = reduce(lambda x,y: x*y, num_list)
Note how the lambda expression takes in two arguments: x and y, and then returns their product, x*y.
请注意,lambda表达式如何接受两个参数:x和y,然后返回其乘积x * y。
Here is a full tutorial on how to use lambda expressions:
这是有关如何使用lambda表达式的完整教程:
使用Reduce的其他示例 (Other Examples of Using Reduce)
There are so many other scenarios of when we can use reduce.
我们可以使用reduce的其他场景还有很多。
For example, we can find the sum of the numbers in a list:
例如,我们可以在列表中找到数字的总和:
num_list = [1,2,3,4,5]sum = reduce(lambda x,y: x + y, num_list)print(sum) #15
Or we can find the maximum number in a list:
或者我们可以在列表中找到最大数量:
num_list = [1,2,3,4,5]max_num = reduce(lambda x,y: x if x > y else y, num_list)print(max_num) #5
Or the minimum number in a list:
或列表中的最小数字:
num_list = [1,2,3,4,5]min_num = reduce(lambda x,y: x if x < y else y, num_list)print(min_num) #1
And so many other applications!
还有许多其他应用!
Note: Python does have built-in functions such as max(), min(), and sum() that would have been easier to use for these three examples. However, the goal was to show how reduce() can be used to accomplish many different tasks.
注意:Python确实具有内置函数,例如max(),min()和sum(),对于这三个示例,它们本来会更容易使用。 但是,目的是说明如何使用reduce()完成许多不同的任务。
结论 (Conclusion)
In this tutorial, we learned how to import and use the reduce function in python. We then saw how lambda expressions can be passed in as an argument to reduce. Lastly, we saw some examples of how reduce can be used.
在本教程中,我们学习了如何在python中导入和使用reduce函数。 然后,我们看到了如何将lambda表达式作为减少的参数传入。 最后,我们看到了一些如何使用reduce的示例。
翻译自: https://towardsdatascience.com/using-reduce-in-python-a9c2f0dede54
python中reduce