Python itertools.accumulate

itertools.accumulate(iterable[, func, *, initial=None])

accumulate 对 iterable 对象逐个进行 func 操作(默认是累加)

注意:accumulate 返回是一个可迭代对象。

>>> from itertools import accumulate
>>> import operator  # operator --- 标准运算符替代函数
>>> a = [1,2,3,4,5]
>>> b = accumulate(a)  # 默认是累加
>>> b   # 这里返回的是一个可迭代对象
<itertools.accumulate object at 0x7f3e5c2f4e48>
>>> list(b)   # 强制转化
[1, 3, 6, 10, 15]

换成乘法

>>> c = accumulate(a, operator.mul)
>>> list(c)
[1, 2, 6, 24, 120]

Python functools.reduce() 函数

Python 内置函数
reduce() 对序列中元素进行累积。

将一个数据集合(链表,元组等)中的所有数据进行下列操作:用函数 func(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 func 函数运算,最后得到一个结果。

注意:Python3.x 需要引入 functools 模块来调用 reduce() 函数:

from functools import reduce

reduce(func, iterable[, initializer])
	func -- 函数,有两个参数
	iterable -- 可迭代对象
	initializer -- 可选,初始参数

返回函数计算结果。

from functools import reduce

sum = reduce(lambda x, y: x + y, [1,2,3,4,5])  
print(sum)
# 15

reduce vs accumulate

reduce

functools 模块用于高阶函数。 作用于或返回其他功能的功能。 就此模块而言,任何可调用对象都可以视为函数。

将两个参数的函数从左到右累计应用于 iterable 的项,以将 iterable 减少为单个值。

functools. reduce(function, iterable, initializer)

如果存在可选的 initializer 值设定项,则将其放在计算中可迭代项的前面,并在可迭代项为空时用作默认值。

如果未给出 initializer 值设定项,并且 iterable 仅包含一项,则返回第一项。

Example :reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

Example 1: Find the product of the list elements using reduce()

from functools import reduce

l1 = [1,2,3,4,5]
reduce(lambda x, y:x*y, l1) # reduce(operator.mul, l1)
# Output:120

Example 2: Find the largest number in the iterable using reduce()

l2 = [15,12,30,4,5]
reduce(lambda x, y: x if x > y else y, l2) # reduce(max, l2)
# Output:30

Example 3:Using User-defined function in reduce()

def sum1(x, y):
    return x + y

reduce(sum1, l2) # reduce(operator.add, l2)
# Output:66

Example 4: Initializer is mentioned.

If the optional initializer is present, it is placed before the items of the iterable in the calculation.

reduce(sum1,l1,10)
# Output:25

Example 5: Iterable contains only one item, reduce() will return that item.

l3 = [5]
reduce(sum1, l3)
# Output:5

l4 = [15]
reduce(lambda x, y:x if x > y else y, l4)
# Output:15

Example 6: If iterable is empty and the initializer is given, reduce() will return the initializer.

l5 = []
reduce(sum1,l5,10)
# Output:10

itertools.accumulate()

Makes an iterator that returns accumulated sum or accumulated results of other binary functions which is mentioned in func-parameter.If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func.-Python documentation

itertools.accumulate(iterable[, func, *, initial=None])

Example 1: By using itertools.accumulate(), we can find the running product of an iterable. The function argument is given as operator.mul.

It will return an iterator that yields all intermediate values. We can convert to list by using a list() constructor.

from itertools import accumulate
import operator  # operator --- 标准运算符替代函数

l1 = accumulate([1,2,3,4,5], operator.mul)
list(l1) # Output:[1, 2, 6, 24, 120]

Example 2: If the function parameter is not mentioned, by default it will perform an addition operation

It will return an iterator that yields all intermediate values. We can convert to list by using list() constructor.

import itertools

#using add operator,so importing operator moduleimport operator
l2 = itertools.accumulate([1,2,3,4,5])
# Output:<itertools.accumulate object at 0x02CD94C8>
#Converting iterator to list object.
list(l2) # Output:[1, 3, 6, 10, 15] # using reduce() for same functionfrom functools import reduce
reduce(operator.add, [1,2,3,4,5])
# Output:15

Example 3: Function argument is given as max(), to find a running maximum

l3 = accumulate([2,4,6,3,1], max)
list(l3) # Output:[2, 4, 6, 6, 6]

Example 4: If the initial value is mentioned, it will start accumulating from the initial value.

#If initial parameter is mentioned, it will start accumulating from the initial value.
#It will contain more than one element in the ouptut iterable.
l4 = accumulate([1,2,3,4,5], operator.add, initial=10)
list(l4) # Output:[10, 11, 13, 16, 20, 25]

Example 5: If the iterable is empty and the initial parameter is mentioned, it will return the initial value.

l5 = accumulate([], operator.add, initial=10)
list(l5) # Output:[10]

Example 6: If iterable contains one element and the initial parameter is not mentioned, it will return that element.

l6 = accumulate([5],lambda x, y:x+y)
list(l6)) # Output:[5]

Example 7: Iterating through the iterator using for loop

Return type is an iterator. We can iterate through iterator using for loop also.

l2 = accumulate([5,6,7],lambda x,y:x+y)
for i in l2:
    print (i)
    '''
	Output:
	5
	11
	18
	'''

Differences between reduce() and accumulate()

Conclusion:
reduce() function is supported by the functools module.
accumulate() function is supported by the itertools module.
reduce() will return only an accumulated value.
accumulate() will return the running accumulated value. Like we can find running max, running product, running sum of an iterable using the accumulate() function.
accumulate() returns an iterator.

Thank you for reading my article, I hope you found it helpful!