Python – Itertools.accumulate()
Python itertools 模块是一组用于处理迭代器的工具。
根据官方文档:
“Module [that] implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML… Together, they form an ‘iterator algebra’ making it possible to construct specialized tools succinctly and efficiently in pure Python.” this basically means that the functions in itertools “operate” on iterators to produce more complex iterators.
简单地说,迭代器是可以在 for 循环中使用的数据类型。 Python中最常见的迭代器是列表。
让我们创建一个字符串列表并将其命名为颜色。我们可以使用 for 循环来迭代列表,例如:
colors = ['red', 'orange', 'yellow', 'green']
# Iterating List
for each in colors:
print(each)
red
orange
yellow
green
有许多不同类型的可迭代对象,但现在,我们将使用列表和集合。
使用 itertools 的要求
使用前必须导入itertools模块。我们还必须导入运算符模块,因为我们想使用运算符。
import itertools
import operator ## only needed if want to play with operators
Itertools模块是函数的集合。我们将探索其中一个累积()函数。
注意:更多信息请参考Python Itertools
积累()
该迭代器有两个参数,可迭代目标和目标中值的每次迭代时将遵循的函数。如果未传递任何函数,则默认情况下会进行添加。如果输入迭代为空,则输出迭代也将为空。
Syntax
itertools.accumulate(iterable[, func]) –> accumulate object
这个函数创建了一个返回函数结果的迭代器。
参数
可迭代和函数
现在理论部分已经足够了,让我们来玩代码
代码:1
# import the itertool module
# to work with it
import itertools
# import operator to work
# with operator
import operator
# creating a list GFG
GFG = [1, 2, 3, 4, 5]
# using the itertools.accumulate()
result = itertools.accumulate(GFG,
operator.mul)
# printing each item from list
for each in result:
print(each)
1
2
6
24
120
解释 :
运算符.mul 接受两个数字并将它们相乘。
operator.mul(1, 2)
2
operator.mul(2, 3)
6
operator.mul(6, 4)
24
operator.mul(24, 5)
120
现在在下一个示例中,我们将使用 max函数,因为它也将函数作为参数。
代码 2:
# import the itertool module
# to work with it
import itertools
# import operator to work with
# operator
import operator
# creating a list GFG
GFG = [5, 3, 6, 2, 1, 9, 1]
# using the itertools.accumulate()
# Now here no need to import operator
# as we are not using any operator
# Try after removing it gives same result
result = itertools.accumulate(GFG, max)
# printing each item from list
for each in result:
print(each)
5
5
6
6
6
9
9
解释:
5
max(5, 3)
5
max(5, 6)
6
max(6, 2)
6
max(6, 1)
6
max(6, 9)
9
max(9, 1)
9
注意:传递函数是可选的,就像你不会传递任何函数一样,默认情况下会相加即相加。
itertools.accumulate(set.difference)
此返回累积集合之间的差异项。
代码解释
# import the itertool module to
# work with it
import itertools
# creating a set GFG1 and GFG2
GFG1 = { 5, 3, 6, 2, 1, 9 }
GFG2 ={ 4, 2, 6, 0, 7 }
# using the itertools.accumulate()
# Now this will first give difference
# and the give result by adding all
# the element in result as by default
# if no function passed it will add always
result = itertools.accumulate(GFG2.difference(GFG1))
# printing each item from list
for each in result:
print(each)
0
4
11