redukcja() w Pythonie

The zmniejsz (zabawa, sekwencja) funkcja jest przyzwyczajona zastosować określoną funkcję przekazaną w jej argumencie do wszystkich elementów listy wspomniane w podanej kolejności. Ta funkcja jest zdefiniowana w narzędzia funkcyjne moduł.

Pracujący :

  • W pierwszym kroku wybierane są dwa pierwsze elementy ciągu i uzyskiwany jest wynik.
  • Następnym krokiem jest zastosowanie tej samej funkcji do wcześniej uzyskanego wyniku i liczby znajdującej się bezpośrednio po drugim elemencie, a wynik zostanie ponownie zapisany.
  • Proces ten trwa do momentu, aż w pojemniku nie pozostanie już więcej elementów.
  • Ostateczny zwrócony wynik jest zwracany i drukowany na konsoli.

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))>

Wyjście

The sum of the list elements is : 17 The maximum element of the list is : 6 

Korzystanie z funkcji operatora

redukcję() można także łączyć z funkcjami operatorowymi, aby uzyskać podobną funkcjonalność jak funkcje lambda i zwiększyć czytelność kodu.

Python3




# 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'> ]))>

Wyjście

The sum of the list elements is : 17 The product of list elements is : 180 The concatenated product is : geeksforgeeks 

zmniejszaj() vs akumuluj()

Do obliczenia sumy elementów sekwencji można użyć funkcji redukcji() i akumulacji(). Istnieją jednak różnice w aspektach wykonawczych w obu przypadkach.

  • redukcja() jest zdefiniowana w module functools, akumuluj() w module itertools.
  • redukcja() przechowuje wynik pośredni i zwraca tylko końcową wartość sumowania. Natomiast akumuluj() zwraca iterator zawierający wyniki pośrednie. Ostatnia liczba zwrócona przez iterator jest wartością sumowania listy.
  • redukcja(zabawa, seq) przyjmuje funkcję jako pierwszy argument, a sekwencję jako drugi argument. W przeciwieństwie do funkcji akumuluj(seq, fun) przyjmuje sekwencję jako pierwszy argument i funkcję jako drugi argument.

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))>

Wyjście

The summation of list using accumulate is :[1, 4, 8, 18, 22] The summation of list using reduce is :22 

redukcja() z trzema parametrami

Funkcja redukcji, tj. funkcja redukcji () działa z 3 parametrami w Pythonie3, a także z 2 parametrami. Mówiąc najprościej, redukcja() umieszcza trzeci parametr przed wartością drugiego, jeśli występuje. Oznacza to zatem, że jeśli drugi argument jest ciągiem pustym, to trzeci argument pełni rolę domyślną.

Oto przykład :(Ten przykład został zaczerpnięty z dokumentacja functools.reduce(). zawiera wersję Pythona funkcji:

Python3




# 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>

Wyjście

15 

Współautorem tego artykułu jest Manjeet Singh (S. Nandini) .