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

