【发布时间】:2016-08-07 17:38:54
【问题描述】:
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)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
if __name__ == '__main__':
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
for a in root.depth_first():
print(a)
# Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)
我认为列表是一个我们可以对其进行迭代的对象,那么为什么要使用 iter() 呢?我是 python 新手,所以这看起来很奇怪。
【问题讨论】:
-
iter不会使列表可迭代,它会返回一个迭代器。
标签: python list python-3.x iterator