2017-06-06 15 views
1

我有三臺發電機。每一個按照時間順序產生結果/事件。
我想要做的是找出哪三個發電機有下一個(年代)的事件。 我的一種方法是從每個生成器獲取一個事件的列表,以及它來自哪個生成器。然後,對列表進行排序,獲取第一個事件,並將相應生成器的下一個事件添加到我的列表中。
有沒有更好/更高效/標準的方式來處理這個問題?從多臺發電機獲取第一個事件

+0

你能舉個例子嗎? – Netwave

回答

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 
+1

謝謝。我認爲必須有一個「標準」的方式來處理這個問題。 –

+0

@GreeTreePython沒問題。爲了使函數更一般化,可以將其定義爲採用第二個參數'key_function',該函數是應用於由迭代器生成的對象以確定優先隊列插入點的函數。即'key = key_function(nxt)'。 – timgeb

相關問題