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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。