詳解Python中迭代器與生成器實例方法
這篇文章主要介紹了Python 中迭代器與生成器實例詳解的相關資料,需要的朋友可以參考下
Python中迭代器與生成器實例詳解
本文透過針對不同應用場景及其解決方案的方式,總結了Python中迭代器與生成器的一些相關知識,具體如下:
1.手動遍歷迭代器
應用場景:想遍歷一個可迭代物件中的所有元素,但是不想用for循環
解決方案:使用next()函數,並擷取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.代理程式迭代
應用場景:想直接在一個包含有列表、元組或其他可迭代物件的容器物件上執行迭代操作
解決方案:定義一個iter()方法,將迭代操作代理到容器內部的物件上
範例:
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): #将迭代请求传递给内部的_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.反向迭代
應用場景:想要反向迭代一個序列
解決方案:使用內建的reversed()函數或在自訂類別上實作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 #常规迭代 def iter(self): n=self.start while n > 0: yield n n -= 1 #反向迭代 def reversed(self): n=1 while n <p style="text-align: left;"><strong>#4.有選擇的迭代</strong></p><p style="text-align: left;">應用場景:想遍歷一個可迭代對象,但是對它開始的某些元素並不感興趣,想跳過</p><p style="text-align: left;">解決方案:使用itertools.dropwhile()</p><p style="text-align: left;">範例1</p><pre class="brush:php;toolbar:false">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.同時迭代多個序列
#應用場景:想同時迭代多個序列每次分別從一個序列中取一個元素
#解決方案:使用zip()函數
#6.不同集合上元素的迭代
#應用場景:想在多個物件執行相同的操作,但是這些物件在不同的容器中
解決方案:使用itertool.chain()函數
### ######7.展開巢狀的序列#########應用程式場景:想將一個多層巢狀的序列展開成一個單層清單######解決方案:使用包含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中迭代器與生成器實例方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

Uvicorn是如何持續監聽HTTP請求的? Uvicorn是一個基於ASGI的輕量級Web服務器,其核心功能之一便是監聽HTTP請求並進�...

攻克Investing.com的反爬蟲策略許多人嘗試爬取Investing.com(https://cn.investing.com/news/latest-news)的新聞數據時,常常�...
