Python使用itertools模塊處理各類(lèi)迭代對(duì)象
引言
在Python的標(biāo)準(zhǔn)庫(kù)中,itertools是一個(gè)處理迭代器的強(qiáng)大模塊,它提供了一系列高效的函數(shù)來(lái)操作和組合迭代對(duì)象。合理使用這些工具能讓代碼更簡(jiǎn)潔、性能更優(yōu),尤其在處理大量數(shù)據(jù)或復(fù)雜迭代邏輯時(shí)優(yōu)勢(shì)顯著。下面詳細(xì)介紹其核心功能及使用場(chǎng)景。
一、無(wú)限迭代器:生成無(wú)窮序列
1. count(start=0, step=1)
功能:從start開(kāi)始,按步長(zhǎng)step生成無(wú)限遞增序列。類(lèi)似于yield生成器,可通過(guò)next函數(shù)獲取元素。當(dāng)然也可以通過(guò)for循環(huán)獲取元素,但是要給一個(gè)退出機(jī)制,否則會(huì)無(wú)限循環(huán)。
案例:生成偶數(shù)序列
from itertools import count
# 生成從2開(kāi)始的偶數(shù)序列(2,4,6,...)
even_nums = count(start=2, step=2)
#使用next函數(shù)獲取元素
print(next(even_nums))
print(next(even_nums))
#for循環(huán)
for i in even_nums:
print(i)
if i == 10000000:
break
# 取前5個(gè)元素
print(list(next(even_nums) for_ in range(5))) # [2, 4, 6, 8, 10]2.cycle(iterable)
功能:無(wú)限循環(huán)迭代對(duì)象iterable中的元素。
案例:循環(huán)交替打印列表內(nèi)的元素
from itertools import cycle
status = cycle(['running', 'paused', 'stopped'])
# 模擬3次狀態(tài)切換
for _ in range(30):
print(next(status)) #running,paused,stopped,running...3.repeat(elem, times=None)
功能:重復(fù)生成elem,times為重復(fù)次數(shù),返回一個(gè)迭代器。
案例:初始化列表
from itertools import repeat # 生成5個(gè)0組成的列表 zeros = list(repeat(0, 5)) # [0, 0, 0, 0, 0] # 與map結(jié)合:計(jì)算多個(gè)數(shù)的平方 squares = list(map(lambda x: x**2, repeat(3, 4))) # [9, 9, 9, 9]
二、迭代器組合工具:高效拼接與分組
1.chain(*iterables)
功能:將多個(gè)迭代器連接成一個(gè)迭代器。
案例:合并列表,元組,集合,字典為一個(gè)迭代器
from itertools import chain
list1 = [1, 2, 'a']
list2 = ('a', 'b')
list3 = {True, False}
list4 = {'a':1, 'v':2}
# 合并為一個(gè)迭代器
merged = chain(list1,list2,list3,list4)
print(list(merged))
#輸出為:
[1, 2, 'a', 'a', 'b', False, True, 'a', 'v']2.groupby(iterable, key=None)
功能:按key函數(shù)分組,返回 (key, group) 元組
案例:按首字母分組單詞(使用時(shí)按照分組規(guī)則先排序)
from itertools import groupby
words = ['apple', 'banana', 'orange', 'avocado', 'berry']
# 務(wù)必先使用sorted排序 然后按首字母分組
for key, group in groupby(sorted(words), key=lambda x: x[0]):
print(f"{key}: {list(group)}")
輸出:
a: ['apple', 'avocado']
b: ['banana', 'berry']
o: ['orange']
#如果不排序,直接使用groupby函數(shù),會(huì)生成重復(fù)的key,與預(yù)期不符
for key, group in groupby(words, key=lambda x: x[0]):
print(f"{key}: {list(group)}")
輸出:
a: ['apple']
b: ['banana']
o: ['orange']
a: ['avocado']
b: ['berry']3.zip_longest(*iterables, fillvalue=None)
功能:類(lèi)似zip,但以最長(zhǎng)迭代器為準(zhǔn),短迭代器用fillvalue填充。
案例:對(duì)齊不同長(zhǎng)度列表
from itertools import zip_longest
names = ['Alice', 'Bob']
ages = [25, 30, 35]
# 填充N(xiāo)one
result = list(zip_longest(names, ages, fillvalue='-'))
print(result) # [('Alice', 25), ('Bob', 30), ('-', 35)]三、排列組合工具:生成序列變體
1.permutations(iterable, r=None)
功能:將迭代對(duì)象生成r長(zhǎng)度的排列(順序不同視為不同元素),r為可選,不傳值,默認(rèn)按照所有元素的長(zhǎng)度進(jìn)行組合。
案例:將字符串按照2個(gè)元素排列
from itertools import permutations
# 生成'ABC'的2元素排列
perms = permutations('ABC', 2)
print(list(perms))
#輸出: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]2.combinations(iterable, r)
功能:將迭代對(duì)象生成r長(zhǎng)度的組合(順序不同會(huì)被視為相同元素), r 為可選,不傳值,默認(rèn)按照所有元素的長(zhǎng)度進(jìn)行組合。
案例:將字符串按照2個(gè)元素排列,生成不重復(fù)組合
from itertools import combinations
# 生成'ABC'的2元素組合
combs = combinations('ABC', 2)
print(list(combs)) # [('A', 'B'), ('A', 'C'), ('B', 'C')]3.product(*iterables, repeat=1)
功能:生成笛卡爾積(所有元素的組合)
案例:生成顏色與尺寸組合
from itertools import product
colors = ['red', 'blue']
sizes = ['S', 'M', 'L']
# 生成所有可能的組合
products = product(colors, sizes)
print(list(products))
#輸出:
[('red', 'S'), ('red', 'M'), ('red', 'L'),
('blue', 'S'), ('blue', 'M'), ('blue', 'L')]
四、篩選工具:過(guò)濾與切片迭代器
1.filterfalse(function, iterable)
功能:保留function返回False的元素。如果不傳function,返回iterable為False的元素。
案例:過(guò)濾掉所有偶數(shù)
fromitertoolsimportfilterfalse numbers=[1,2,3,4,5,6] # 保留奇數(shù) odds=filterfalse(lambdax:x%2==0,numbers) print(list(odds)) #輸出: [1, 3, 5]
案例:返回False的元素
from itertools import filterfalse numbers = [1, 2, 3, 4, 5, 0,'',False,True] # 保留奇數(shù) odds = filterfalse(None,numbers) print(list(odds)) #輸出:[0, '', False]
2.islice(iterable, start, stop, step=1)
功能:類(lèi)似列表切片,支持迭代器切片
案例:取迭代器中間元素
from itertools import islice, count # 生成從1開(kāi)始的無(wú)限序列 nums = count(1) # 取第3到第7個(gè)并且步長(zhǎng)為2的元素,相當(dāng)于取第3個(gè),第5個(gè),第7個(gè)元素(索引從0開(kāi)始) sliced = islice(nums, 2, 7, 2) print(list(sliced)) # 輸出:[3, 5, 7]
3.takewhile(function, iterable)
功能:當(dāng)function返回True時(shí)繼續(xù)提取元素,否則停止
案例:取小于5的數(shù)
fromitertoolsimporttakewhile numbers=[1,3,5,2,4,6] # 取小于5的數(shù) result=takewhile(lambdax:x<5,numbers) print(list(result)) #輸出: [1, 3]
五、多工具組合實(shí)戰(zhàn)
案例:生成不重復(fù)的隨機(jī)排列
from itertools import permutations, islice
import random
# 生成1-10的隨機(jī)排列
def random_permutation(n):
numbers = list(range(1, n+1))
# 打亂順序后生成排列
random.shuffle(numbers)
return list(islice(permutations(numbers), 1))[0]
print("隨機(jī)排列:", random_permutation(5))
#輸出 例如: (3, 1, 5, 2, 4)案例:高效統(tǒng)計(jì)單詞頻率
from itertools import groupby
from collections import Counter
text = "apple banana apple orange banana apple"
words = text.split()
# 按單詞分組并統(tǒng)計(jì)數(shù)量
word_groups = groupby(sorted(words))
word_count = {word: len(list(group)) for word, group in word_groups}
print("單詞頻率:", word_count) # {'apple': 3, 'banana': 2, 'orange': 1}
# 更簡(jiǎn)潔方式:結(jié)合Counter
print("Counter統(tǒng)計(jì):", Counter(words))
#輸出:
單詞頻率: {'apple': 3, 'banana': 2, 'orange': 1}
Counter統(tǒng)計(jì): Counter({'apple': 3, 'banana': 2, 'orange': 1})通過(guò)靈活組合itertools中的工具,能大幅提升迭代操作的效率和代碼簡(jiǎn)潔性。建議在處理海量數(shù)據(jù)、復(fù)雜組合邏輯或需要優(yōu)化內(nèi)存占用時(shí)優(yōu)先考慮這些工具,避免重復(fù)造輪子。
以上就是Python使用itertools模塊處理各類(lèi)迭代對(duì)象的詳細(xì)內(nèi)容,更多關(guān)于Python itertools處理類(lèi)迭代對(duì)象的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python學(xué)習(xí)之while 循環(huán)語(yǔ)句
這篇文章主要給大家介紹了關(guān)于Python中while循環(huán)語(yǔ)句的相關(guān)資料,使用while循環(huán)語(yǔ)句可以解決程序中需要重復(fù)執(zhí)行的操作,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-10-10
詳解pytest+Allure搭建方法以及生成報(bào)告常用操作
本文主要介紹了詳解pytest+Allure搭建方法以及生成報(bào)告常用操作,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
python刪除文件夾下相同文件和無(wú)法打開(kāi)的圖片
這篇文章主要為大家詳細(xì)介紹了python刪除文件夾下相同文件和無(wú)法打開(kāi)的圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
使用Python輕松構(gòu)建一個(gè)Windows11系統(tǒng)智能垃圾清理系統(tǒng)
Windows 11雖然引入了存儲(chǔ)感知,但在面對(duì)深層開(kāi)發(fā)緩存、老舊更新殘留及特定應(yīng)用日志時(shí)往往力不從心,本文將詳解如何使用Python編寫(xiě)一套安全、智能、可配置的自動(dòng)化清理腳本,有需要的小伙伴可以了解下2026-01-01
Python中使用uv創(chuàng)建環(huán)境及原理舉例詳解
uv是Astral團(tuán)隊(duì)開(kāi)發(fā)的高性能Python工具,整合包管理、虛擬環(huán)境、Python版本控制等功能,這篇文章主要介紹了Python中使用uv創(chuàng)建環(huán)境及原理的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-06-06
python中的?sorted()函數(shù)和sort()方法區(qū)別
這篇文章主要介紹了python中的?sorted()函數(shù)和sort()方法,首先看sort()方法,sort方法只能對(duì)列表進(jìn)行操作,而sorted可用于所有的可迭代對(duì)象。具體內(nèi)容需要的小伙伴可以參考下面章節(jié)2022-02-02

