如果标题措辞不当,我很抱歉,我不确定如何说出来。我有一个基本上迭代2维可迭代的第二维的函数。以下是简单的复制:
words = ['ACGT', 'TCGA']
def make_lists():
for i in range(len(words[0])):
iter_ = iter([word[i] for word in words])
yield iter_
lists = list(make_lists())
for list_ in lists:
print(list(list_))
运行此输出:
['A', 'T']
['C', 'C']
['G', 'G']
['T', 'A']
我想生成生成器而不必评估words
,以防words
非常长,所以我尝试了以下内容:
words = ['ACGT', 'TCGA']
def make_generators():
for i in range(len(words[0])):
gen = (word[i] for word in words)
yield gen
generators = list(make_iterator())
for gen in generators:
print(list(gen))
但是,运行输出:
['T', 'A']
['T', 'A']
['T', 'A']
['T', 'A']
我不确定到底发生了什么。我怀疑它与生成器理解有关,在屈服时没有缩小其范围,因此它们都是共享的。如果我在一个单独的函数中创建生成器并从该函数返回,它似乎可以工作。