欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python yield from 反向迭代,迭代代码

程序员文章站 2022-05-20 21:37:16
...
from collections import deque


class LindeHistory:
    def __init__(self, lines, histlen=3):
        self.lines = lines
        self.history = deque(maxlen=histlen)

    def __iter__(self):
        yield from (line for _, line in enumerate(self.lines, 1))

    def __reversed__(self):
        yield from (self.lines[line] for line in range(len(self.lines) - 1, -1, -1))

    def clear(self):
        self.history.clear()


lines = ['morgan', 'lions'] * 10
for x in reversed(LindeHistory(lines)):
    print(x)

iter 迭代器
reversed 反向迭代