python实现node迭代和反向迭代

一.实现Node迭代

构建了一个自定义容器Node对象,里面包含有列表、元组或其他可迭代对象,可以通过定义一个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)

    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 ch in root.depth_first():
        print(ch)

result如下:

Node(0)
Node(1)
Node(3)
Node(4)
Node(2)
Node(5)

Process finished with exit code 0

总结:Python 的迭代协议要求一个 iter () 方法返回一个特殊的迭代器对象,这个迭代器对象实现了 next () 方法并通过 StopIteration 异常标识迭代的完成.

二.反向迭代

可以通过在自定义类上实现迭代.如下:

class Countdown:
    
    def __init__(self, start):
        self.start = start
        

    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1

    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1

def use_count():
    for val in reversed(Countdown(10)):
        print(val)
    print("--------------")
    for val in Countdown(10):
        print(val)

if __name__ == "__main__":
    use_count()

result如下:

1
2
3
4
5
6
7
8
9
10
--------------
10
9
8
7
6
5
4
3
2
1

Process finished with exit code 0

总结:定义一个反向迭代器可以使得代码非常的高效,因为它不再需要将数据填充到一个
列表中然后再去反向迭代这个列表

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值