一、iter方法的基本用法
在Python中,我們經常需要對可迭代對象進行遍歷,比如列表、元組、字典、集合等。Python中提供了一個iter()方法,用於將可迭代對象轉換為迭代器對象。迭代器對象可以逐個返回可迭代對象中的元素,而不是將整個可迭代對象讀入內存。
# 使用iter方法將列錶轉換為迭代器 lst = [1, 2, 3] lst_iter = iter(lst) # 遍歷迭代器對象 for item in lst_iter: print(item)
調用iter()方法返回的迭代器對象可以使用next()方法逐個返回元素,直到沒有更多元素可迭代,此時會拋出StopIteration異常。
# 遍歷迭代器對象 lst_iter = iter(lst) while True: try: item = next(lst_iter) print(item) except StopIteration: break
使用迭代器對象遍歷可迭代對象可以讓我們在讀取數據時不必一次性將整個數據集讀入內存,有效節省內存消耗。
二、iter方法在循環中的應用
在Python的for循環中,實際上也是調用了iter()方法將可迭代對象轉換為迭代器對象,並且使用next()方法逐個返回元素。
# for循環遍歷列表 lst = [1, 2, 3] for item in lst: print(item)
如果我們在循環中使用多個可迭代對象,則需要藉助zip()方法來打包可迭代對象,將它們轉換為一個可迭代的元組序列。
# 同時遍歷兩個列表 lst1 = [1, 2, 3] lst2 = ['a', 'b', 'c'] for item1, item2 in zip(lst1, lst2): print(item1, item2)
在Python 3中,zip()方法返回的是一個迭代器對象,使用時也需要調用next()方法逐個返回元素。
# zip方法返回的是一個迭代器對象 lst1 = [1, 2, 3] lst2 = ['a', 'b', 'c'] zip_iter = zip(lst1, lst2) # 遍歷迭代器對象 while True: try: item1, item2 = next(zip_iter) print(item1, item2) except StopIteration: break
三、iter方法在自定義類中的應用
在自定義類中,如果我們希望實現可迭代對象,則需要提供一個__iter__()方法。該方法需要返回一個迭代器對象,該對象需要提供__next__()方法,以便在迭代過程中逐個返回數據。
# 自定義可迭代對象 class MyIterable: def __init__(self, data): self.data = data def __iter__(self): self.index = 0 return self def __next__(self): if self.index >= len(self.data): raise StopIteration item = self.data[self.index] self.index += 1 return item # 使用自定義可迭代對象 my_iterable = MyIterable([1, 2, 3]) for item in my_iterable: print(item)
在自定義類中,如果希望提供一個可迭代對象的倒序遍歷方法,可以實現一個__reversed__()方法,並返回一個可迭代對象的逆序迭代器。
# 自定義可迭代對象和逆序迭代器 class MyIterable: def __init__(self, data): self.data = data def __iter__(self): self.index = 0 return self def __next__(self): if self.index >= len(self.data): raise StopIteration item = self.data[self.index] self.index += 1 return item def __reversed__(self): self.index = len(self.data) - 1 return self def __next__(self): if self.index < 0: raise StopIteration item = self.data[self.index] self.index -= 1 return item # 使用自定義可迭代對象和逆序迭代器 my_iterable = MyIterable([1, 2, 3]) for item in reversed(my_iterable): print(item)
四、使用itertools模塊構建高效的迭代器
Python的itertools模塊提供了一系列的工具函數,可以快速地構建高效的迭代器。
- count方法可以創建一個無限迭代器,可以使用islice()方法截取指定區間內的元素。
- cycle方法可以創建一個無限迭代器,循環返回可迭代對象中的元素。可以使用islice()方法截取指定區間內的元素。
- repeat方法可以創建一個無限迭代器,返回指定元素n次。可以使用islice()方法截取指定區間內的元素。
- chain方法可以將多個可迭代對象鏈接成一個迭代器對象,逐個返回元素。需要使用from_iterable()方法將可迭代對象轉換為迭代器對象。
- compress方法可以根據另一個布爾序列的值,過濾出對應位置上值為True的元素。
from itertools import count, islice # 構建無限迭代器 counter = count(1, 2) # 使用islice方法截取部分元素 for item in islice(counter, 5): print(item) # 輸出結果:1, 3, 5, 7, 9
from itertools import cycle, islice # 構建無限迭代器 cycler = cycle('abc') # 使用islice方法截取部分元素 for item in islice(cycler, 5): print(item) # 輸出結果:a, b, c, a, b
from itertools import repeat, islice # 構建無限迭代器 repeater = repeat('hello', 3) # 使用islice方法截取部分元素 for item in repeater: print(item) # 輸出結果:hello, hello, hello
from itertools import chain # 鏈接多個列表成為迭代器對象 lst1 = [1, 2, 3] lst2 = [4, 5, 6] lst3 = [7, 8, 9] chain_iter = chain.from_iterable([lst1, lst2, lst3]) # 遍歷迭代器對象 for item in chain_iter: print(item) # 輸出結果:1, 2, 3, 4, 5, 6, 7, 8, 9
from itertools import compress # 過濾出奇數位置上的元素 data = [1, 2, 3, 4, 5, 6] filter_list = [True, False, True, False, True, False] filter_iter = compress(data, filter_list) # 遍歷迭代器對象 for item in filter_iter: print(item) # 輸出結果:1, 3, 5
五、總結
使用iter()方法可以將可迭代對象轉換為迭代器對象,逐個返回元素而不是一次性讀取整個數據集。
在Python中的for循環實際上也是使用迭代器方式遍歷可迭代對象。
在自定義類中,可以通過__iter__()方法和__next__()方法實現可迭代對象的遍歷方法。
Python的itertools模塊提供了一系列的輔助函數,可以幫助我們快速構建高效的迭代器。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/250771.html