Python 中迭代器與生成器實(shí)例詳解
Python 中迭代器與生成器實(shí)例詳解
本文通過針對不同應(yīng)用場景及其解決方案的方式,總結(jié)了Python中迭代器與生成器的一些相關(guān)知識,具體如下:
1.手動遍歷迭代器
應(yīng)用場景:想遍歷一個可迭代對象中的所有元素,但是不想用for循環(huán)
解決方案:使用next()函數(shù),并捕獲StopIteration異常
def manual_iter():
with open('/etc/passwd') as f:
try:
while True:
line=next(f)
if line is None:
break
print(line,end='')
except StopIteration:
pass
#test case items=[1,2,3] it=iter(items) next(it) next(it) next(it)
2.代理迭代
應(yīng)用場景:想直接在一個包含有列表、元組或其他可迭代對象的容器對象上執(zhí)行迭代操作
解決方案:定義一個iter()方法,將迭代操作代理到容器內(nèi)部的對象上
示例:
class Node:
def __init__(self,value):
self._value=value
self._children=[]
def __repr__(self):
return 'Node({!r})'.fromat(self._value)
def add_child(self,node):
self._children.append(node)
def __iter__(self):
#將迭代請求傳遞給內(nèi)部的_children屬性
return iter(self._children)
#test case
if __name='__main__':
root=Node(0)
child1=Node(1)
child2=Nide(2)
root.add_child(child1)
root.add_child(child2)
for ch in root:
print(ch)
3.反向迭代
應(yīng)用場景:想要反向迭代一個序列
解決方案:使用內(nèi)置的reversed()函數(shù)或者在自定義類上實(shí)現(xiàn)reversed()
示例1
a=[1,2,3,4]
for x in reversed(a):
print(x) #4 3 2 1
f=open('somefile')
for line in reversed(list(f)):
print(line,end='')
#test case
for rr in reversed(Countdown(30)):
print(rr)
for rr in Countdown(30):
print(rr)
示例2
class Countdown:
def __init__(self,start):
self.start=start
#常規(guī)迭代
def __iter__(self):
n=self.start
while n > 0:
yield n
n -= 1
#反向迭代
def __reversed__(self):
n=1
while n <= self.start:
yield n
n +=1
4.有選擇的迭代
應(yīng)用場景:想遍歷一個可迭代對象,但是對它開始的某些元素并不感興趣,想跳過
解決方案:使用itertools.dropwhile()
示例1
with open('/etc/passwd') as f:
for line in f:
print(line,end='')
示例2
from itertools import dropwhile
with open('/etc/passwd') as f:
for line in dropwhile(lambda line:line.startwith('#'),f):
print(line,end='')
5.同時迭代多個序列
應(yīng)用場景:想同時迭代多個序列每次分別從一個序列中取一個元素
解決方案:使用zip()函數(shù)




6.不同集合上元素的迭代
應(yīng)用場景:想在多個對象執(zhí)行相同的操作,但是這些對象在不同的容器中
解決方案:使用itertool.chain()函數(shù)

7.展開嵌套的序列
應(yīng)用場景:想將一個多層嵌套的序列展開成一個單層列表
解決方案:使用包含yield from語句的遞歸生成器
示例
from collections import Iterable
def flatten(items,ignore_types=(str,bytes)):
for x in items:
if isinstance(x,Iterable) and not isinstance(x,ignore_types):
yield from flatten(x)
else:
yield x
#test case items=[1,2,[3,4,[5,6],7],8] for x in flatten(items): print(x)
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
- 深入講解Python中的迭代器和生成器
- python的迭代器與生成器實(shí)例詳解
- Python中生成器和迭代器的區(qū)別詳解
- 舉例講解Python中的迭代器、生成器與列表解析用法
- Python3中的列表生成式、生成器與迭代器實(shí)例詳解
- 老生常談Python之裝飾器、迭代器和生成器
- 解析Python中的生成器及其與迭代器的差異
- Python中的迭代器與生成器高級用法解析
- python生成器,可迭代對象,迭代器區(qū)別和聯(lián)系
- 淺談Python中的可迭代對象、迭代器、For循環(huán)工作機(jī)制、生成器
- python生成器/yield協(xié)程/gevent寫簡單的圖片下載器功能示例
- python 協(xié)程中的迭代器,生成器原理及應(yīng)用實(shí)例詳解
相關(guān)文章
PyTorch實(shí)現(xiàn)ResNet50、ResNet101和ResNet152示例
今天小編就為大家分享一篇PyTorch實(shí)現(xiàn)ResNet50、ResNet101和ResNet152示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python使用Redis實(shí)現(xiàn)作業(yè)調(diào)度系統(tǒng)(超簡單)
Redis作為內(nèi)存數(shù)據(jù)庫的一個典型代表,已經(jīng)在很多應(yīng)用場景中被使用,這里僅就Redis的pub/sub功能來說說怎樣通過此功能來實(shí)現(xiàn)一個簡單的作業(yè)調(diào)度系統(tǒng)。這里只是想展現(xiàn)一個簡單的想法,所以還是有很多需要考慮的東西沒有包括在這個例子中,比如錯誤處理,持久化等2016-03-03
Python英文文章詞頻統(tǒng)計(jì)(14份劍橋真題詞頻統(tǒng)計(jì))
這篇文章主要介紹了Python英文文章詞頻統(tǒng)計(jì)(14份劍橋真題詞頻統(tǒng)計(jì)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10

