在Python編程世界中,理解Python的迭代器和生成器
相關的任何對像都與a [
每個生成器都是迭代器,但不是vice vicea。發電機是通過調用包含一個或多個產量表達式的函數來構建的。這些產量表達式暫時暫停該函數的執行和返回值。 The resulting object possesses the characteristics of an iterator, but its implementation is unique.When to Use Iterators vs. Generators
Custom Iterators: Opt for a custom iterator when you require a custom class with intricate state-tracking or need to expose additional methods beyond __next __。 生成器通常更合適,更簡單地實現了大多數方案,尤其是當狀態維護最小的情況下。產量表達式處理框架懸浮和恢復,使管理狀態毫不費力。
實際示例:生成平方數字考慮在給定範圍內生成平方數的任務。 對於我的範圍(開始,停止): 收益i * i#使用屈服來暫停和返回值[&& && && && &&華氏度isterator imparination:[&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&華 def __init __(自我,開始,停止): self.start = start self.Stop =停止 def __iter __(自我): 返回自我 def __next __(self): 如果self.start> = self.Stop: 提高停止 current = self.start * self.start self.start = 1 返回當前[&& && &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& && && && &&華
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3