Python generator conflicting with list

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])]
    # 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)

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!

? , , ?

+4
3

python lexical scoping. "" :

funcs = [ lambda: i for i in range(3) ]
print(funcs[0]())
=> 2  #??
print(funcs[1]())
=> 2  #??
print(funcs[2]())
=> 2

- .

, "" :

def make_gen(i):
    return (x[i] for x in copies[i])
dropped_copies = [make_gen(i) for i in range(2)]

i , make_gen, . " i", ( i).

+3

shx2, :

dropped_copies = [(lambda j: (x[j] for x in copies[j]))(i) for i in range(2)]

, . , - :

dropped_copies = [(lambda i: (x[i] for x in copies[i]))(i) for i in range(2)]

, , for:

dropped_copies = []
for i in range(2):
    dropped_copies.append((x[i] for x in copies[i]))

, , .

+2

, dropped_copies - , , i 1.

, :

dropped_copies = [[x[i] for x in copies[i]] for i in range(2)]
0
source

Source: https://habr.com/ru/post/1598825/


All Articles