【问题标题】:Dynamic Generator in PythonPython中的动态生成器
【发布时间】:2021-03-13 22:09:33
【问题描述】:

我需要创建一个可以管理动态资源的服务(我正在考虑一个正在增长的动态 csv。在这种情况下,我使用了一个列表以便更容易理解),从一个可迭代对象中返回下一个项目.

如果列表完成,输出将为 False,我需要等待添加元素。

当元素最终添加时,生成器应该生成新添加的项目(这是我无法理解的部分)。

a_lst = [1, 2]


class DynamicGenerator:
    """
    Generic Generator that return item by item from a_lst and
    can append a new item when needed.
    """
    def __init__(self):
        global a_lst

    def gen_lst(self):
        for item in a_lst:
            yield item

    def grow_lst(self, new_item):
        a_lst.append(new_item)

class AvailableNextIterator:
    """
    Return next item from iterable if it's available,
    else return False.
    """
    def __init__(self, iterable):
        self.iterator = iterable

    def __next__(self):
        return next(self.iterator, False)


dg = DynamicGenerator()
gl = dg.gen_lst()

it = AvailableNextIterator(gl)

print(it.__next__())
print(it.__next__())
print(it.__next__())

dg.grow_lst(3)

print(it.__next__())

这是代码输出:

1
2
False
False

这是我需要的输出:

1
2
False
3

【问题讨论】:

    标签: python dynamic iterator generator


    【解决方案1】:

    很简单,您在添加最后一项之前用尽了迭代;您已经触发了gen_list 的数据结束异常。您已经退出循环,并且没有重新进入的规定。您可以在该方法中通过一些简单的跟踪来看到这一点:

    def gen_lst(self):
        for item in a_lst:
            yield item
        print("gen_lst is out of data")
        yield "over the cliff's edge ..."
    

    现在,输出是

    1
    2
    gen_lst is out of data
    over the cliff's edge ...
    False
    

    您似乎想要一个 FIFO 队列;我建议您使用现成包中的可用数据结构,而不是尝试自己动手。

    但是,如果这是家庭作业:

    1. 按照 SO 发布标准的要求,标记您的问题;
    2. 研究现有实现。

    将队列维护为实例的属性,而不是外部变量。您的“生成器”应该直接检查队列,而不是依赖for 来管理迭代。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 2014-08-23
      • 2013-10-02
      相关资源
      最近更新 更多