0
Please explain the logic
import functools list=[1,2,3,4,5] R_list=[functools.reduce(lambda x,y: x*y,list)] print(R_list)
4 Antworten
+ 6
functools.reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
Source: https://docs.python.org/3/library/functools.html
+ 3
functools.reduce execute a function with items of an iterable by passing couple of parameter starting from left to right of iterable then passing the result of function and next item for next function call while all items are processed, then return the result. In yourexample, this happen:
1) first two items are multiplied 1*2=2
2) the result is multiplied for 3rd items 2*3= 6
3) the result is multiplied for 4th items 6*4= 24
4) the result is multiplied for 5th items 24*5= 120
5) functools.reduce return 120
For more details see here
https://docs.python.org/3/library/functools.html