What is the 'pythonic' equivalent to the 'fold' function from functional programming?

后端 未结 9 2011
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 00:03

What is the most idiomatic way to achieve something like the following, in Haskell:

foldl (+) 0 [1,2,3,4,5]
--> 15

Or its equivalent in

9条回答
  •  醉梦人生
    2020-12-01 00:21

    In Python 3, the reduce has been removed: Release notes. Nevertheless you can use the functools module

    import operator, functools
    def product(xs):
        return functools.reduce(operator.mul, xs, 1)
    

    On the other hand, the documentation expresses preference towards for-loop instead of reduce, hence:

    def product(xs):
        result = 1
        for i in xs:
            result *= i
        return result
    

提交回复
热议问题