Loading

《Python Cookbook v3.0.0》Chapter4 迭代器、生成器

感谢:
https://github.com/yidao620c/python3-cookbook
如有侵权,请联系我整改。

本文章节会严格按照原书(以便和原书对照,章节标题可能会略有修改),内容会有增删。

4.1 手动遍历迭代器

>>> items
[1, 2, 3]
>>> it=iter(items)
>>> it
<list_iterator object at 0x0000024B94D25408>
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration
>>> it=iter(items)
>>> next(it)
1
>>> print(*it)
2 3
>>> print(*it)

4.2 代理迭代

class中定义 __iter__()

class Node:
  def __init__(self, value):
    self._value = value
    self._children = []
  def __repr__(self):
    return 'Node({!r})'.format(self._value)
  def add_child(self, node):
    self._children.append(node)
  def __iter__(self):
    return iter(self._children)

4.3 使用生成器创建新的迭代模式

示例,

def frange(start, stop, increment):
  x = start
  while x < stop:
    yield x
    x += increment
>>> for n in frange(0, 4, 0.5):
... print(n)
>>> list(frange(0, 1, 0.125))
[0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
>>> f=frange(0,1,0.2)
>>> next(f)
0
>>> next(f)
0.2
>>> next(f)
0.4
>>> next(f)
0.6000000000000001
posted @ 2021-08-21 18:25  wwcg2235  阅读(38)  评论(0)    收藏  举报