El reducir (diversión, secuencia) La función se utiliza para aplicar una función particular pasada en su argumento a todos los elementos de la lista mencionado en la secuencia transmitida. Esta función está definida en herramientas funcionales módulo.
Laboral :
- En el primer paso, se seleccionan los dos primeros elementos de la secuencia y se obtiene el resultado.
- El siguiente paso es aplicar la misma función al resultado obtenido previamente y el número que sigue al segundo elemento y el resultado se almacena nuevamente.
- Este proceso continúa hasta que no quedan más elementos en el contenedor.
- El resultado final devuelto se devuelve y se imprime en la consola.
Python3
# python code to demonstrate working of reduce()> > # importing functools for reduce()> import> functools> > # initializing list> lis> => [> 1> ,> 3> ,> 5> ,> 6> ,> 2> ]> > # using reduce to compute sum of list> print> (> 'The sum of the list elements is : '> , end> => '')> print> (functools.> reduce> (> lambda> a, b: a> +> b, lis))> > # using reduce to compute maximum element from list> print> (> 'The maximum element of the list is : '> , end> => '')> print> (functools.> reduce> (> lambda> a, b: a> if> a>b> else> b, lis))> |
>
usuarios de la lista mysql
>Producción
The sum of the list elements is : 17 The maximum element of the list is : 6>
Uso de funciones de operador
reduce() también se puede combinar con funciones de operador para lograr una funcionalidad similar a la de las funciones lambda y hace que el código sea más legible.
Python3
pitón __dict__
# python code to demonstrate working of reduce()> # using operator functions> > # importing functools for reduce()> import> functools> > # importing operator for operator functions> import> operator> > # initializing list> lis> => [> 1> ,> 3> ,> 5> ,> 6> ,> 2> ]> > # using reduce to compute sum of list> # using operator functions> print> (> 'The sum of the list elements is : '> , end> => '')> print> (functools.> reduce> (operator.add, lis))> > # using reduce to compute product> # using operator functions> print> (> 'The product of list elements is : '> , end> => '')> print> (functools.> reduce> (operator.mul, lis))> > # using reduce to concatenate string> print> (> 'The concatenated product is : '> , end> => '')> print> (functools.> reduce> (operator.add, [> 'geeks'> ,> 'for'> ,> 'geeks'> ]))> |
>
incluir programación c
>Producción
The sum of the list elements is : 17 The product of list elements is : 180 The concatenated product is : geeksforgeeks>
reducir() vs acumular()
Tanto reduce() como acumula() se pueden utilizar para calcular la suma de los elementos de una secuencia. Pero en ambos casos existen diferencias en los aspectos de implementación.
- reducir() se define en el módulo functools, acumular() en el módulo itertools.
- reduce() almacena el resultado intermedio y solo devuelve el valor de suma final. Mientras que acumular() devuelve un iterador que contiene los resultados intermedios. El último número del iterador devuelto es el valor sumatorio de la lista.
- reduce(fun, seq) toma la función como primer argumento y la secuencia como segundo argumento. Por el contrario, acumular(seq, fun) toma la secuencia como primer argumento y funciona como segundo argumento.
Python3
# python code to demonstrate summation> # using reduce() and accumulate()> > # importing itertools for accumulate()> import> itertools> > # importing functools for reduce()> import> functools> > # initializing list> lis> => [> 1> ,> 3> ,> 4> ,> 10> ,> 4> ]> > # printing summation using accumulate()> print> (> 'The summation of list using accumulate is :'> , end> => '')> print> (> list> (itertools.accumulate(lis,> lambda> x, y: x> +> y)))> > # printing summation using reduce()> print> (> 'The summation of list using reduce is :'> , end> => '')> print> (functools.> reduce> (> lambda> x, y: x> +> y, lis))> |
>
>Producción
The summation of list using accumulate is :[1, 4, 8, 18, 22] The summation of list using reduce is :22>
función reducir() con tres parámetros
miflixr
La función Reducir, es decir, la función reducir() funciona con 3 parámetros en python3, así como con 2 parámetros. Para decirlo de forma sencilla, reduce() coloca el tercer parámetro antes del valor del segundo, si está presente. Por lo tanto, significa que si el segundo argumento es una secuencia vacía, entonces el tercer argumento sirve como predeterminado.
Aquí hay un ejemplo :(Este ejemplo ha sido tomado del documentación de functools.reduce() incluye una versión Python de la función:
Python3
chmod 755
# Python program to illustrate sum of two numbers.> def> reduce> (function, iterable, initializer> => None> ):> > it> => iter> (iterable)> > if> initializer> is> None> :> > value> => next> (it)> > else> :> > value> => initializer> > for> element> in> it:> > value> => function(value, element)> > return> value> > # Note that the initializer, when not None, is used as the first value instead of the first value from iterable , and after the whole iterable.> tup> => (> 2> ,> 1> ,> 0> ,> 2> ,> 2> ,> 0> ,> 0> ,> 2> )> print> (> reduce> (> lambda> x, y: x> +> y, tup,> 6> ))> > # This code is contributed by aashutoshjha> |
>
>Producción
15>
Este artículo es una contribución de Manjeet Singh (S. Nandini) .