How do I merge two python iterators?

前端 未结 13 1263
花落未央
花落未央 2020-12-06 09:29

I have two iterators, a list and an itertools.count object (i.e. an infinite value generator). I would like to merge these two into a resulting ite

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 10:12

    I also agree that itertools is not needed.

    But why stop at 2?

      def tmerge(*iterators):
        for values in zip(*iterators):
          for value in values:
            yield value
    

    handles any number of iterators from 0 on upwards.

    UPDATE: DOH! A commenter pointed out that this won't work unless all the iterators are the same length.

    The correct code is:

    def tmerge(*iterators):
      empty = {}
      for values in itertools.izip_longest(*iterators, fillvalue=empty):
        for value in values:
          if value is not empty:
            yield value
    

    and yes, I just tried it with lists of unequal length, and a list containing {}.

提交回复
热议问题