【问题标题】:Need to implement the Python itertools function "chain" in a class需要在一个类中实现Python itertools函数“chain”
【发布时间】:2019-10-27 12:32:09
【问题描述】:

我正在尝试在 python 的 itertools 中模拟“链”函数。

我想出了以下生成器。

# 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    

如何在一个类中模拟相同的功能? 由于函数的输入是任意数量的列表,我不确定是否可以在类中使用打包/解包,如果可以,我不确定如何在 'init' 方法中解包.

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

谢谢。

【问题讨论】:

  • “我不确定打包/解包在使用类时是否有用”我不确定使用打包/解包的位置如何影响其有用性
  • 我的意思是它是否可以在课堂上使用。更新了问题。
  • 是的,它可以....
  • 怎么样?有什么建议或参考吗?
  • def chain_for(*a):def __init__(self, *a): 之间没有(太大)区别

标签: python class itertools chain


【解决方案1】:

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]

【讨论】:

  • 我在这里看到了三个主要缺陷。首先,这既不是迭代器,也不是可重用的迭代器。 Second, it breaks if any of the inputs are empty. 第三,使用yield 打败了编写类的意义——几乎为这种事情编写类的唯一原因是作为如何手动管理迭代器状态的学习练习。
  • @user2357112 "almost the only reason to write a class for this kind of thing is as a learning exercise in how to manage iterator state manually" 这显然是这个问题的前提,否则为什么有人会尝试重新实现经过良好测试的 stdlib 代码。您评论的另外两点正是我在回答中使用“一种非常粗暴的方式”这个短语的原因
  • 那你为什么用yield
  • @user2357112 因为我觉得?为什么这有关系?欢迎您发布不使用yield 的答案。我从来没有说过使用yield 是回答这个问题的唯一/最正确的方法。
  • 如果你使用yield,你不是手动管理迭代器状态。你让发电机悬挂机制为你做这件事。这打败了你刚才所说的显然是问题的重点。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 2010-11-10
  • 2020-12-10
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多