I worked in Python with generator functions. I want to write a function that takes a generator whose values were tuples and returns a list of generators where each generator value corresponds to one index in the original tuple.
I currently have a function that does this for a fixed number of elements in a tuple. Here is my code:
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])]
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)
This splits the generator correctly, leading to left_words containing left halves and right_words containing right halves.
, , . , , , left_words, right_words , :
Left halves:
lo,
y
me
s
ed!
Right halves:
lo,
y
me
s
ed!
? , , ?