前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 手动迭代iter/next

python 手动迭代iter/next

作者头像
用户5760343
发布2019-09-30 18:27:04
4320
发布2019-09-30 18:27:04
举报
文章被收录于专栏:sktjsktj
代码语言:javascript
复制
with open('/etc/passwd') as f:
 while True:
 line = next(f, None)
 if line is None:
 break
 print(line, end='')

代码语言:javascript
复制
 items = [1, 2, 3]
 Get the iterator
 it = iter(items) # Invokes items.iter()
 Run the iterator
 next(it) # Invokes it.next()
 1
 next(it)
 2
 next(it)
 3
 next(it)
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 StopIteration

类实现迭代iter

class Node: def init(self, value): self._value = value self._children = []

代码语言:javascript
复制
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)

Example

if name == 'main': root = Node(0) child1 = Node(1) child2 = Node(2) root.add_child(child1) root.add_child(child2) # Outputs Node(1), Node(2) for ch in root: print(ch

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.09.29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 类实现迭代iter
  • Example
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档