reduce() în Python

The reduce(distracție,seq) funcția este obișnuită aplică o anumită funcție transmisă în argumentul său tuturor elementelor listei menționate în secvența transmisă de-a lungul. Această funcție este definită în functools modul.

De lucru:

  • La prima etapă, sunt selectate primele două elemente ale secvenței și se obține rezultatul.
  • Următorul pas este să aplicați aceeași funcție rezultatului obținut anterior și numărului care urmează celui de-al doilea element și rezultatul este din nou stocat.
  • Acest proces continuă până când nu mai sunt lăsate elemente în container.
  • Rezultatul final returnat este returnat și tipărit pe consolă.

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

Ieșire

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

Utilizarea funcțiilor operatorului

reduce() poate fi, de asemenea, combinat cu funcții de operator pentru a obține funcționalitatea similară cu funcțiile lambda și face codul mai ușor de citit.

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

Ieșire

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

reduce() vs acumula()

Atât reduce() cât și accumulate() pot fi folosite pentru a calcula sumarea elementelor unei secvențe. Dar există diferențe în aspectele de implementare în ambele.

  • reduce() este definit în modulul functools, accumulate() în modulul itertools.
  • reduce() stochează rezultatul intermediar și returnează doar valoarea finală de însumare. În timp ce acumulate() returnează un iterator care conține rezultatele intermediare. Ultimul număr al iteratorului returnat este valoarea de însumare a listei.
  • reduce(fun, seq) ia funcția ca primul argument și secvența ca al doilea argument. Spre deosebire de accumulate(seq, fun) ia secvența ca prim argument și funcționează ca al doilea 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))>

Ieșire

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

funcția reduce() cu trei parametri

Funcția reducere, adică funcția reduce() funcționează cu 3 parametri în python3, precum și pentru 2 parametri. Pentru a spune într-un mod simplu reduce() plasează al 3-lea parametru înaintea valorii celui de-al doilea, dacă este prezent. Astfel, înseamnă că dacă al 2-lea argument este o secvență goală, atunci al 3-lea argument servește ca cel implicit.

Iată un exemplu :(Acest exemplu a fost preluat de la documentația functools.reduce(). include o versiune Python a funcției:

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>

Ieșire

15 

Acest articol este contribuit de Manjeet Singh (S. Nandini) .