【问题标题】:Get The First Event From More Than One Generator从多个生成器获取第一个事件
【发布时间】:2017-06-06 11:34:36
【问题描述】:

我有三个发电机。每一个都按时间顺序产生结果/事件。
我想要做的是找出三个生成器中的哪一个具有下一个(按时间顺序)事件。 我想到的一种方法是列出来自每个生成器的一个事件,以及它来自哪个生成器。然后,对列表进行排序,取第一个事件,并将对应生成器中的下一个事件添加到我的列表中。
有没有更好/更有效/标准的方法来处理这个问题?

【问题讨论】:

  • 你能举个例子吗?

标签: python iterator generator


【解决方案1】:

由于您没有给出具体示例,我只能为您提供一些想法/伪代码。这个想法是在内存中最多保存来自n 迭代器的n 项目,因为每个迭代器都会产生按时间顺序排序的对象。此外,插入/获取 PriorityQueue 将比一遍又一遍地排序列表更快。

from Queue import PriorityQueue

def yield_chronologically(iterators):
    'iterators: list of iterator objects'
    PQ = PriorityQueue()

    # put first n items
    for i, it in enumerate(iterators):
        try:
            nxt = next(it)            
            # this is where you have to determine the priority
            # with a function get_chronological_key you have yet to write
            chronological_key = get_chronological_key(nxt) 
            PQ.put(chronological_key, (i, nxt))
        except StopIteration:
            pass

    # yield items and insert next item from iterator that was taken from
    # into the PQ
    while not PQ.empty():
        _, (i, nxt) = PQ.get()
        yield nxt
        try:
            nxt = next(iterators[i])                
            chronological_key = get_chronological_key(nxt)
            PQ.put(chronological_key, (i, nxt))
        except StopIteration:
            pass

【讨论】:

  • 谢谢。我认为必须有一种“标准”的方式来处理这个问题。
  • @GreeTreePython 没问题。为了使函数更通用,您可以将其定义为采用第二个参数key_function,该参数应用于迭代器产生的对象以确定优先级队列插入点。 IE。 key = key_function(nxt).
猜你喜欢
  • 1970-01-01
  • 2022-06-26
  • 1970-01-01
  • 2018-12-13
  • 2014-07-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多