在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