需要在 class 中实现 Python itertools 函数 "chain"

Need to implement the Python itertools function "chain" in a class

我正在尝试在 python 中模拟 itertools 中的 "chain" 函数。

我想出了下面的生成器。

# Chain make an iterator that returns elements from the first iterable
# until it is exhausted, then proceeds to the next iterable, until all
# of the iterables are exhausted.
def chain_for(*a) :
    if a :
       for i in a :
          for j in i :
             yield j
    else :
       pass    

如何在 class 中模拟相同的功能? 由于函数的输入是任意数量的列表,我不确定 packing/unpacking 是否可以在 classes 中使用,如果可以,我不确定如何在 '[=23] 中解压=]init'方法。

class chain_for :
   def __init__(self, ...) :
      ....
   def __iter__(self) :
      self
   def __next__(self) :
      .....

谢谢。

def chain_for(*a):def __init__(self, *a): 之间没有(太多)差异。 因此,一个非常粗略的实现方式可以是:

class chain_for:
    def __init__(self, *lists):
        self.lists = iter(lists)
        self.c = iter(next(self.lists))

    def __iter__(self):
        while True:
            try:
                yield next(self.c)
            except StopIteration:
                try:
                    self.c = iter(next(self.lists))
                except StopIteration:
                    break
                yield next(self.c)

chain = chain_for([1, 2], [3], [4, 5, 6])
print(list(chain))

输出:

[1, 2, 3, 4, 5, 6]