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模块是函数的集合。我们将探索这些accumulate()函数之一。
注意:有关更多信息,请参阅Python Itertools。
accumulate()
此迭代器有两个参数,可迭代的目标和目标中每次值迭代时将遵循的函数。如果未传递任何函数,则默认情况下会进行添加。如果输入iterable为空,则输出iterable也将为空。
用法
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
说明:
operator.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 fiest give difference
# and the give result by adding all
# the elemet in result as by default
# if no fuction 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
相关用法
注:本文由纯净天空筛选整理自YashKhandelwal8大神的英文原创作品 Python – Itertools.accumulate()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。