Python的內(nèi)建模塊itertools的使用解析
itertools模塊
itertools 是python的迭代器模塊,itertools提供的工具相當(dāng)高效且節(jié)省內(nèi)存。Python的內(nèi)建模塊itertools提供了非常有用的用于操作迭代對象的函數(shù)。
使用這些工具,你將能夠創(chuàng)建自己定制的迭代器用于高效率的循環(huán)。
無限迭代器
(1)count(初值=0, 步長=1):
count 迭代器會返回從傳入的起始參數(shù)開始的均勻間隔的數(shù)值。count 也可以接收指定的步長參數(shù)。
"""count(初值,步長)"""
from itertools import count
for i in count(10, 2): # 從10開始,每步長隔2,無限循環(huán)(此案例演示大于100退出)
if i > 100:
break
else:
print(i) # 打印結(jié)果:10,12,14,16,18,...,98,100(2)islice(iterable,start,stop,步長):
從 10 開始,輸出 5 個元素后結(jié)束。islice 的第二個參數(shù)控制何時停止迭代。但其含義并不是”達(dá)到數(shù)字 5 時停止“,而是”當(dāng)?shù)?5 次之后停止“。
"""isslice(迭代器,迭代次數(shù))"""
from itertools import islice
for i in islice(count(10), 5):
print(i) # 打印結(jié)果:10,11,12,13,14
for j in islice([1, 2, 3, 4, 5], 2):
print(j) # 打印結(jié)果:1,2 (3)cycle:
這里我們創(chuàng)建了一個 for 循環(huán),使其在三個字母 XYZ 間無限循環(huán)。當(dāng)然,我們并不真地想要永遠(yuǎn)循環(huán)下去,所以我們添加了一個簡單的計數(shù)器來跳出循環(huán)。
from itertools import cycle
count = 0
for item in cycle('XYZ'):
if count > 7:
break
print(item) # X,Y,Z,X,Y,Z,X,Y
count += 1(4)repeat():
負(fù)責(zé)把一個元素?zé)o限重復(fù)下去,不過如果提供第二個參數(shù)就可以限定重復(fù)次數(shù):
from itertools import repeat
for i in repeat('1', 5):
print(i) # 1,1,1,1,1可終止迭代器
(1)accumulate(可迭代對象[, 函數(shù)])
accumulate 迭代器將返回累計求和結(jié)果,或者傳入兩個參數(shù)的話,由傳入的函數(shù)累積計算的結(jié)果。默認(rèn)設(shè)定為相加
from itertools import accumulate
for i in accumulate(range(7)):
print(i) # 0,1,3,6,10,15,21
for i in accumulate([1, 2, 3, 4, 5], lambda x, y: x * y):
print(i) # 1,2,6,24,120(2)chain(*可迭代對象)
chain 迭代器能夠?qū)⒍鄠€可迭代對象合并成一個更長的可迭代對象。
from itertools import chain x = chain(range(3), range(3, 5), [5, 6, 7], (8, 9), '11') print(list(x)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '1', '1']
(3)groupby() groupby()把迭代器中相鄰的重復(fù)元素挑出來放在一起:
from itertools import groupby
for key, group in groupby('AAABBBCCAAA'):
print(key, list(group))
# 結(jié)果:
"""
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
"""也可以使用函數(shù),按照分組函數(shù)的值對元素進(jìn)行分組
from itertools import groupby
x = groupby(range(10), lambda x: x < 5 or x > 8)
for condition, numbers in x:
print(condition, list(numbers))
# 結(jié)果:
"""
True [0, 1, 2, 3, 4]
False [5, 6, 7, 8]
True [9]
"""(4)itertools.combinations(可迭代對象,組合個數(shù))
求列表或生成器中指定數(shù)目的元素不重復(fù)的所有組合。
(5)itertools.combinations_with_replacement(可迭代對象,組合個數(shù)) 允許重復(fù)元素的組合
from itertools import combinations, combinations_with_replacement
x = combinations(['A', 'B', 'C'], 2)
y = combinations_with_replacement(['A', 'B', 'C'], 2)
print(list(x)) # [('A', 'B'), ('A', 'C'), ('B', 'C')]
print(list(y)) # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')](6)itertools.permutations(可迭代對象,組合個數(shù)) 產(chǎn)生指定數(shù)目的元素的所有排列(順序有關(guān))
from itertools import permutations
x = permutations(['A', 'B', 'C'], 3)
print(list(x)) # [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]itertools中combinations與permutations函數(shù)區(qū)別
import itertools s = [1, 2, 3] print(itertools.permutations(s, 2)) # 結(jié)果是一個迭代器 print(itertools.combinations(s, 2)) # 結(jié)果是一個迭代器 print(list(itertools.permutations(s, 2))) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] print(list(itertools.combinations(s, 2))) # [(1, 2), (1, 3), (2, 3)]
permutations和combinations都是得到一個迭代器。
combinations方法重點在組合,permutations方法重在排列。
到此這篇關(guān)于Python的內(nèi)建模塊itertools的使用解析的文章就介紹到這了,更多相關(guān)Python的itertools內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于OpenCV與Python實現(xiàn)的身份證號碼識別案例詳解
身份證識別技術(shù)主要依賴于計算機(jī)視覺和圖像處理技術(shù),通過對身份證圖像進(jìn)行分析,提取關(guān)鍵信息(如身份證號碼、姓名等),這篇文章主要介紹了基于OpenCV與Python實現(xiàn)的身份證號碼識別的相關(guān)資料,需要的朋友可以參考下2026-01-01
5道關(guān)于python基礎(chǔ) while循環(huán)練習(xí)題
這篇文章主要給大家分享的是5道關(guān)于python基礎(chǔ) while循環(huán)練習(xí)題,無論學(xué)習(xí)什么語言,練習(xí)都是必不可少的,下面文章的練習(xí)題挺精湛的,需要的朋友可以參考一下2021-11-11
Python+Pygame實戰(zhàn)之文字劇情游戲的實現(xiàn)
這篇文章主要為大家詳細(xì)介紹了如何利用Python和Pygame實現(xiàn)兩款文字劇情游戲——《巨龍之洞》和《太空礦工》,感興趣的小伙伴可以了解一下2022-12-12
Python?LeNet網(wǎng)絡(luò)詳解及pytorch實現(xiàn)
LeNet主要用來進(jìn)行手寫字符的識別與分類,并在美國的銀行中投入了使用。本文主要為大家詳細(xì)介紹了LetNet以及通過pytorch實現(xiàn)LetNet,感興趣的小伙伴可以學(xué)習(xí)一下2021-11-11
django model通過字典更新數(shù)據(jù)實例
這篇文章主要介紹了django model通過字典更新數(shù)據(jù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
一分鐘帶你上手Python調(diào)用DeepSeek的API
最近DeepSeek非常火,作為一枚對前言技術(shù)非常關(guān)注的程序員來說,自然都想對接DeepSeek的API來體驗一把,下面小編就來為大家介紹一下Python如何快速上手調(diào)用DeepSeek?API吧2025-02-02

