我一直在用生成器函数搞乱Python。我想写一个函数,它使用一个其值为元组的生成器,并返回一个生成器列表,其中每个生成器的值对应于原始元组中的一个索引。Python生成器与列表理解冲突
目前,我有一个函数为元组中的硬编码元素实现此功能。这里是我的代码:
import itertools
def tee_pieces(generator):
copies = itertools.tee(generator)
dropped_copies = [(x[0] for x in copies[0]), (x[1] for x in copies[1])]
# dropped_copies = [(x[i] for x in copies[i]) for i in range(2)]
return dropped_copies
def gen_words():
for i in "Hello, my name is Fred!".split():
yield i
def split_words(words):
for word in words:
yield (word[:len(word)//2], word[len(word)//2:])
def print_words(words):
for word in words:
print(word)
init_words = gen_words()
right_left_words = split_words(init_words)
left_words, right_words = tee_pieces(right_left_words)
print("Left halves:")
print_words(left_words)
print("Right halves:")
print_words(right_words)
这正确地分裂发生器,导致left_words包含左半部分和right_words包含右半部分。
问题出现在我尝试使用上面注释过的行参数化要创建的发电机数量时。据我所知,应该是等价的,但是当我使用该行代替,既left_words和right_words最终方含字的右半边,给人这样的输出:
Left halves:
lo,
y
me
s
ed!
Right halves:
lo,
y
me
s
ed!
这究竟是为什么?我怎样才能适应期望的结果,即参数化将发生器分成几部分?
谢谢,这很好地解决了它。 – isaacg